检查 3 个点是否在同一条线上
我想知道一段代码,它实际上可以告诉我 2D 空间中的 3 个点是否在同一条线上。伪代码也足够了,但 Python 更好。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以检查 ABC 三角形的面积是否为 0:
当然,您实际上不需要除以 2。
You can check if the area of the ABC triangle is 0:
Of course, you don't actually need to divide by 2.
这是 C++,但您可以将其改编为 python:
基本上,我们正在检查点 1 和点 2 以及点 1 和点 3 之间的斜率是否匹配。斜率是 y 的变化除以 x 的变化,因此我们有:
交叉相乘得到
(y1 - y2) * (x1 - x3) == (y1 - y3) * (x1 - x2)
;请注意,如果您使用双打,您可以检查 epsilon:
This is C++, but you can adapt it to python:
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:
Cross multiplying gives
(y1 - y2) * (x1 - x3) == (y1 - y3) * (x1 - x2)
;Note, if you are using doubles, you can check against an epsilon:
y - y0 = a(x-x0)
(1) 而a = (y1 - y0)/(x1 - x0)
和A(x0, y0) )
B(x1,y1)
C(x2,y2)
。查看C
是否满足(1)。您只需替换适当的值即可。详细信息
y - y0 = a(x-x0)
(1) whilea = (y1 - y0)/(x1 - x0)
andA(x0, y0)
B(x1, y1)
C(x2, y2)
. See whetherC
statisfies (1). You just replace the appropriate values.Details
阅读此,并用它来查找通过前两点的直线方程。按照说明查找
m
和b
。然后对于第三点,计算mx + b - y
。如果结果为零,则第三个点与前两个点在同一直线上。Read this, and use it to find the equation of a line through the first two points. Follow the instructions to find
m
andb
. Then for your third point, calculatemx + b - y
. If the result is zero, the third point is on the same line as the first two.规则 1:在任何线性二维空间中,两个点始终在同一条线上。
取 2 个点并建立一个方程来表示穿过它们的一条线。
然后检查第三个点是否也在该线上。
祝你好运。
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.