Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check is a point (x,y) is between two points drawn on a straight line

Tags:

java

line

I have drawn a line between two points A(x,y)---B(x,y) Now I have a third point C(x,y). I want to know that if C lies on the line which is drawn between A and B. I want to do it in java language. I have found couple of answers similar to this. But, all have some problems and no one is perfect.

like image 713
Usman Mahmood Avatar asked Jul 17 '13 06:07

Usman Mahmood


People also ask

How do you check if a point lies on a line between two points?

To find out if a point (x, y) is on the graph of a line, we plug in the values and see if we get a true statement, such as 10 = 10. If we get something different, like 6 = 4, we know that the point is not on the line because it does not satisfy the equation.

How do you check if a point lies on a line C++?

Approach: In order for the given point to lie on the line, it must satisfy the equation of the line. Check whether y = (m * x) + c holds true. Below is the implementation of the above approach: C++


1 Answers

if (distance(A, C) + distance(B, C) == distance(A, B))     return true; // C is on the line. return false;    // C is not on the line. 

or just:

return distance(A, C) + distance(B, C) == distance(A, B); 

The way this works is rather simple. If C lies on the AB line, you'll get the following scenario:

A-C------B 

and, regardless of where it lies on that line, dist(AC) + dist(CB) == dist(AB). For any other case, you have a triangle of some description and 'dist(AC) + dist(CB) > dist(AB)':

A-----B  \   /   \ /    C 

In fact, this even works if C lies on the extrapolated line:

C---A-------B 

provided that the distances are kept unsigned. The distance dist(AB) can be calculated as:

  ___________________________  /           2              2 V (A.x - B.x)  + (A.y - B.y) 

Keep in mind the inherent limitations (limited precision) of floating point operations. It's possible that you may need to opt for a "close enough" test (say, less than one part per million error) to ensure correct functioning of the equality.

like image 95
WoooHaaaa Avatar answered Oct 14 '22 12:10

WoooHaaaa