我有一个点 pos =(x,y)的坐标,我需要检查它是否是通过两点的直线的一部分 p1 =( x1,y1),p2 =(x2,y2)。 我使用的公式是y - y1 =((x - x1)/(x2 - x1))*(y2 - y1),代码是:
if pos[1] - p1[1] - 10 <= ((pos[0] - p1[0]) / (p2[0] - p1[0])) * (p2[1] - p1[1]) <= pos[1] - p1[1] + 10:
return True
我通过检查画布的每个点(使用tkinter)得到了这个:
p1 = (313, 215)
p2 = (92, 44)
for x in range(0, 400):
for y in range(0, 300):
if y - p1[1] - 5 <= ((x - p1[0]) / (p2[0] - p1[0])) * (p2[1] - p1[1]) <= y - p1[1] + 5:
canvas.create_oval(x, y, x, y)
最大的一个是由上面的等式表示的线,手绘的是我想要的。
我也试过在地理代数上测试它,但是一切正常......我想念什么?
答案 0 :(得分:1)
你的数学似乎是正确的,问题就是解释。
首先,您可以简化数学运算:
x1,y1 = p1
x2,y2 = p2
m = (y2-y1)/(x2-x1)
def f(x): return y1 + m*(x-x1)
def test(x,y,tol = 10):
return abs(y-f(x)) <= tol
然后只使用test(x,y)
或test(*pol)
。
问题是在画布坐标中,增加y
实际上会让你在画布上移动。在您的示例数据中 - 正确绘制线条,因为连接画布点(313, 215)
和(92,44)
的线段是一条递减线。
也许您想将点数绘制为(x,300-y)
而不是(x,y)
。
答案 1 :(得分:1)
class Solution {
public boolean checkStraightLine(int[][] coordinates) {
float slope =0;
if(coordinates.length==1)
return false;
else if(coordinates.length==2)
return true;
else{
for (int i = 0; i < coordinates.length - 2 ; i++) {
int y1 = coordinates[i+1][1] -coordinates[i][1];
int y2 = coordinates[i+2][1] -coordinates[i+1][1];
int x1 = coordinates[i+1][0] -coordinates[i][0];
int x2 = coordinates[i+2][0] -coordinates[i+1][0];
if(y1*x2!=y2*x1){
return false;
}
}
}
return true;
}
}
答案 2 :(得分:0)
使用if y=m*x+n:
其中x
和y
是该点的坐标,m
是斜率,n
是(x上的系数?I)我不是母语为英语的人。使用m=(y2-y1)/(x2-x1)
计算斜率。
如果两个点恰好位于相同的X坐标中,那么只需检查另一个点是否也在上面,但不要检查Y.
要知道n
使用Gauss&#39;( - Jordan)方法/消除的价值。