我在資料框中得到ValueError: math domain error了一些要點。我知道 acos 取值從 -1 到 1。我嘗試使用 decimal.Decimal 函式解決錯誤。但它仍然為相同的點拋出錯誤。
def angle(p1,p2,p3):
dot_product = np.dot(p2-p1,p3-p2)
vec1 = np.linalg.norm(p2-p1)
vec2 = np.linalg.norm(p3-p2)
x = dot_product /(vec1 * vec2)
return round(math.degrees(math.acos(x)),2)
def get_angle(points):
return [[angle(point1[0], point1[1], point2[1]) for point2 in points.values] for point1 in points.values]
# this is the column on which i'm apply the function
# this is one of the sample group
# I have to find angle between the co-ordinates
# function return a list of angles w.r.t other points
points
[[-140.78063986473717, 91.91634474415332], [-142.34375254437327, 87.6819673711434]]
[[-141.25677946582437, 94.60493099503219], [-142.7676919612568, 90.44367777556181]]
[[-138.125714250491, 86.75676850322634], [-139.46260946977418, 82.95679492782801]]
[[-137.67089835880324, 74.81029774621129], [-139.08569156355225, 70.57744785398245]]
例如,
p1 = np.array([-138.125714250491, 86.75676850322634])
p2 = np.array([-139.46260946977418, 82.95679492782801])
p3 = np.array([-132.35878855874762, 95.67247487790883])
math.degrees(math.acos(np.dot(p2-p1,p3-p2)/(np.linalg.norm(p2-p1) * np.linalg.norm(p3-p2))))
>>> 170.19212016382508
添加x = Decimal(dot_product /(vec1 * vec2))并不能解決問題
我認為罪魁禍首是乘法和除法運算,這使得資料幀中某些點的結果高于 1 和低于 -1。如何解決這個問題呢?
uj5u.com熱心網友回復:
如果 的值x超出區間 [-1, 1] 的很小一部分——由于正常的浮點不精確——你可以在將值傳遞給acos. 類似的東西acos(max(min(x, 1), -1))應該可以作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/511853.html
上一篇:通過字典小寫傳遞條件無法識別
