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.
问题:
回答1:
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.
回答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;
}
回答3:
y - y0 = a(x-x0)
(1) while a = (y1 - y0)/(x1 - x0)
and A(x0, y0)
B(x1, y1)
C(x2, y2)
. See whether C
statisfies (1). You just replace the appropriate values.
Details
回答4:
Rule 1: In any linear 2d space, two points are always on the same line.
Take 2 points and build an equation that represents a line through them. Then check if the third point is also on that line.
Good luck.
回答5:
Read this, and use it to find the equation of a line through the first two points. Follow the instructions to find m
and b
. Then for your third point, calculate mx + b - y
. If the result is zero, the third point is on the same line as the first two.