又是一個新的問題。
一個判斷點是否在線段上的題。這個題的上一個題是通過判斷點在線段的左、中、右三個方向。按原書中的內容編寫程序。發現和原書的完全不一樣。我最后在今天找到了一個比較合理的答案,非常感謝寫這個公式的作者,謝謝
以下,是我截取他文章的內容。
怎么判斷坐標為(xp,yp)的點P是在直線的哪一側呢?
設直線是由其上兩點(x1,y1),(x2,y2)確定的,直線方向是由(x1,y1)到(x2,y2)的方向。
假設直線方程為:Ax+By+C=0,則有:
A=y2-y1; B=x1-x2; C=x2y1-x1y2;
這時可以通過計算D,來判斷點P是在直線的哪一側:
D=Axp+Byp+C
若D<0,則點P在直線的左側;若D>0,則點P在直線的右側;若D=0,則點P在直線上。
我利用這個算法修正了,確定點在左、中、右三個方向時,原書中的錯誤。
但是我繼續有這個公式做下一個題,也就是確定點是否在線段上的時候。這個公式又不好使了。
接下來我截取一下兩個題的內容
見下圖
現在4.31題我的PYTHON程序如下
p0X, p0Y = eval(input("Enter coordinates for the p0 is x,y "))
p1X, p1Y = eval(input("Enter coordinates for the p1 is x,y "))
p2X, p2Y = eval(input("Enter coordinates for the p2 is x,y "))
a = p1Y - p0Y
b = p0X - p1X
c = p1X * p0Y - p0X * p1Y
d = (a * p2X) + (b * p2Y) +c
if d < 0:
print(“p2 is on the left side of the line from p0 to p1”)
elif d > 0:
print(“p2 is on the right side of the line from p0 to p1”)
elif d == 0:
print(“p2 is on the same line from p0 to p1”)
4.32題的PYTHON程序如下:
x0, y0 = eval(input("Enter coordinates for the p0 is x,y "))
x1, y1 = eval(input("Enter coordinates for the p1 is x,y "))
x2, y2 = eval(input("Enter coordinates for the p2 is x,y "))
a = y1-y0
b = x0-x1
c = x1 * y0 - x0 * y1
d = (a * x2) + (b * y2) + c
if d == 0:
print(f"{x2, y2} is on the line segment from {x0, y0} to {x1, y1}")
else:
print(f"{x2, y2} is not on the line segment from {x0, y0} to {x1, y1}")
現在的問題是輸入4.32題的測試結果,2個結果全都是點在線段上。
我開始懷疑是不是我的條件有問題。但是從4.31來看d <0 , >0, =0的結果都是對的。所以這個疑問讓我有些琢磨不透。