【发布时间】:2018-02-12 13:40:26
【问题描述】:
我正在尝试按照 Gareth Rees 的出色说明实现一个函数来在 python 中查找射线/线段交叉点: https://stackoverflow.com/a/14318254/7235455 和 https://stackoverflow.com/a/565282/7235455
这是我的功能:
from math import radians, sin, cos
import numpy as np
def find_intersection(point0, theta, point1, point2):
# convert arguments to arrays:
p = np.array(point0, dtype=np.float) # ray origin
q = np.array(point1, dtype=np.float) # segment point 1
q2 = np.array(point2, dtype=np.float) # segment point 2
r = np.array((cos(theta),sin(theta))) # theta as vector (= ray as vector)
s = q2 - q # vector from point1 to point2
rxs = np.cross(r,s)
qpxs = np.cross(q-p,s)
qpxr = np.cross(q-p,r)
t = qpxs/rxs
u = qpxr/rxs
if rxs == 0 and qpxr == 0:
t0 = np.dot(q-p,r)/np.dot(r,r)
t1 = np.dot(t0+s,r)/np.dot(r,r)
return "collinear"
elif rxs == 0 and qpxr != 0:
return "parallel"
elif rxs != 0 and 0 <= t and 0 <= u and u <= 1: # removed t <= 1 since ray is inifinte
intersection = p+t*r
return "intersection is {0}".format(intersection)
else:
return None
当有交叉路口时,该功能可以正常工作。但它不承认并行性或共线性,因为条件 rxs == 0 和 qpxr == 0 不(曾经?)满足。运行例如:
p0 = (0.0,0.0)
theta = radians(45.0)
p1 = (1.0,1.0)
p2 = (3.0,3.0)
c = find_intersection(p0,theta,p1,p2)
返回无。在 if 块给出之前添加 rxs 和 qpxr 的打印语句
rxs = 2.22044604925e-16 qpxr = -1.11022302463e-16
我的结论是,由于浮点问题,该函数无法捕获第一个 if 语句的条件。 2.22044604925e-16 和 -1.11022302463e-16 非常小,但不幸的是不完全是 0。我知道浮点数不能有二进制的精确表示。
我的结论是正确的还是我遗漏了什么?有什么想法可以避免这个问题吗? 非常感谢!
【问题讨论】:
标签: python floating-point geometry floating-accuracy