Home > Article > Backend Development > How to determine whether three coordinates are collinear
I'm sure my question is a very general one, probably a pure java question. However, I've been trying to find a way to identify if three coordinates are collinear, using the same logic and found that it doesn't seem to work for the example with "point" as input. Two methods can be used 1. Find the area of the triangle forming three coordinates/points. If they are on the same line; the area value must be zero. 2. Divide the line connecting these coordinates into two parts and find their respective slopes. If they are on the same line, the slopes will be the same.
Here's what I'm trying.
private boolean collinearCheck( Coordinate endPointOne , Coordinate intersection,Coordinate endPointTwo ){ boolean isCollenear = false; //Area of triangle approach double area = (Math.round(endPointOne.x )* (Math.round(intersection.y) - Math.round (endPointTwo.y)) + Math.round(intersection.x )* (Math.round(endPointTwo.y) - Math.round (endPointOne.y)) + Math.round(endPointTwo.x) * (Math.round(endPointOne.y) - Math.round(intersection.y))); if((endPointOne.x * (intersection.y - endPointTwo.y) + intersection.x * (endPointTwo.y - endPointOne.y) + endPointTwo.x * (endPointOne.y - intersection.y))<= 0) if(Math.round(area) <= 0) { isCollenear = true; } // Slope Approach double numeratorOne = Math.round(intersection.y) - Math.round(endPointOne.y); double denominatorOne = Math.round(intersection.x) - Math.round(endPointOne.x); double numeratorTwo = Math.round(endPointTwo.y) - Math.round(intersection.y); double denominatorTwo = Math.round(endPointTwo.x) - Math.round(intersection.x); double result1 = Math.round(numeratorOne/denominatorOne); double result2 = Math.round(numeratorTwo/denominatorTwo); if(result1== 0 && result2==0){ isCollenear = true; } return isCollenear; }
In both cases, using coordinates as input; even for similarly collinear cases, I end up with values for the area, such as 4, etc. For cases that are clearly not collinear; I end up with the same slope value.
Is there a way to get an explicit notifier for collinearity using any construct? Am I doing it right? The coordinate sample values I pass to the method are Coefficient endPointOne = -26.666666666666686, 32.38095238095238 ....etc
Looking forward to your opinions.
Thanks and greetings
I am not checking the area code, but checking whether the three points are collinear. Then the formula is:
Point (x1,y1), (x2,y2), (x3,y3).
It should be collinear if and only if,
(y2-y1) (y3-y2) ------- = ------- (x2-x1) (x3-x2)
So the code should be,
if(result1==result2){ isCollenear = true; }
The above is the detailed content of How to determine whether three coordinates are collinear. For more information, please follow other related articles on the PHP Chinese website!