I want to know a piece of a code which can actually tell me if 3 points in a 2D space are on the same line or not. A pseudo-code is also sufficient but Python is better.
Three points are collinear if the value of the area of the triangle formed by the three points is zero. Substitute the coordinates of the given three points in the area of the triangle formula. If the result for the area of the triangle is zero, then the given points are said to be collinear.
From any point in the list (e.g. first one) if all other points have the same slope with that one, then they are on the same line.
You can check if the area of the ABC triangle is 0:
[ Ax * (By - Cy) + Bx * (Cy - Ay) + Cx * (Ay - By) ] / 2
Of course, you don't actually need to divide by 2.
This is C++, but you can adapt it to python:
bool collinear(int x1, int y1, int x2, int y2, int x3, int y3) { return (y1 - y2) * (x1 - x3) == (y1 - y3) * (x1 - x2); }
Basically, we are checking that the slopes between point 1 and point 2 and point 1 and point 3 match. Slope is change in y divided by change in x, so we have:
y1 - y2 y1 - y3 ------- = -------- x1 - x2 x1 - x3
Cross multiplying gives (y1 - y2) * (x1 - x3) == (y1 - y3) * (x1 - x2)
;
Note, if you are using doubles, you can check against an epsilon:
bool collinear(double x1, double y1, double x2, double y2, double x3, double y3) { return fabs((y1 - y2) * (x1 - x3) - (y1 - y3) * (x1 - x2)) <= 1e-9; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With