-
Mathematically :
As explained in wikipedia
the shortest distance between a line and a dot, can be calculated as
follows:
If the line passes through two points P1=(x1,y1) and P2=(x2,y2) then the distance of (x0,y0) from the line is:
-
Java implimentaion
class Point { double x,y; Point(double pX, double pY){ this.x= pX; this.y= pY; } public double distance(Point A1, Point A2){ double numerator = Math.abs((A2.y - A1.y)*this.x + (A2.x - A1.x)*this.y + A2.x*A1.y - A2.y*A1.x); double denominator = Math.sqrt(Math.pow(A2.y - A1.y,2) + Math.pow(A2.x - A1.x,2)); return numerator/denominator; } }
To calculate the distance between Point B
and the line defined by Points A1
and A2
, you use the method distance
like this:
public static void main (String[] args) throws java.lang.Exception
{
Point A1 = new Point(0,3);
Point A2 = new Point(2,0);
Point B = new Point(0,0);
System.out.println(
B.distance(A1,A2)
);
}
And here is the code up and running in ideone.
But pleas go buck to the basics, chose some good and funny coding book or tut and give it a go, happy coding 🙂
solved How to calculate shortest distance from path?