Gia*_*ear 4 python geometry coding-style line
考虑下面的交叉线示例:
l1 = ((20,5),(40,20))
l2 = ((20,20),(40,5))
l3 = ((30,30),(30,5)) # vertical line
Run Code Online (Sandbox Code Playgroud)
我开发了以下代码来计算交叉点的x,y(参见理论细节)
def gradient(l):
"""Returns gradient 'm' of a line"""
m = None
# Ensure that the line is not vertical
if l[0][0] != l[1][0]:
m = (1./(l[0][0]-l[1][0]))*(l[0][1] - l[1][1])
return m
def parallel(l1,l2):
if gradient(l1) != gradient(l2):
return False
return True
def intersect(l):
"""Returns intersect (b) of a line using the equation of
a line in slope and intercepet form (y = mx+b)"""
return l[0][1] - (gradient(l)*l[0][0])
def line_intersection(l1,l2):
"""Returns the intersection point (x,y) of two line segments. Returns False
for parallel lines"""
# Not parallel
if not parallel(l1,l2):
if gradient(l1) is not None and gradient(l2) is not None:
x = (1./(gradient(l1) - gradient(l2))) * (intersect(l2) - intersect(l1))
y = (gradient(l1)*x) + intersect(l1)
else:
if gradient(l1) is None:
x = l1[0][0]
y = (gradient(l2)*x) + intersect(l2)
elif gradient(l2) is None:
x = l2[0][0]
y = (gradient(l1)*x) + intersect(l1)
return (x,y)
else:
return False
Run Code Online (Sandbox Code Playgroud)
示例会话:
>>> line_intersection(l1,l2)
(30.0, 12.5)
>>> line_intersection(l2,l3)
(30, 12.5)
Run Code Online (Sandbox Code Playgroud)
我希望以有效的方式改进我的代码,对于长度有限的线段,它们可能实际上并不相交.
l1 = ((4,4),(10,10))
l2 = ((11,5),(5,11))
l3 = ((11,5),(9,7))
line_intersection(l1,l2) #valid
(8.0, 8.0)
line_intersection(l1,l3) # they don't cross each other
(8.0, 8.0)
line_intersection(l2,l3) #line parallel
False
Run Code Online (Sandbox Code Playgroud)
我不太优雅的解决方案是以下.
def crosses(l1,l2):
if not parallel(l1,l2):
x = line_intersection(l1,l2)[0]
xranges = [max(min(l1[0][0],l1[1][0]),min(l2[0][0],l2[1][0])),min(max(l1[0][0],l1[1][0]),max(l2[0][0],l2[1][0]))]
if min(xranges) <= x <= max(xranges):
return True
else:
return False
else:
return False
crosses(l1,l2)
True
crosses(l2,l3)
False
Run Code Online (Sandbox Code Playgroud)
我在寻找是否有可能在python中改进我的函数的风格
unu*_*tbu 17
在我的书中,任何返回正确答案的代码都非常棒.做得好.
以下是一些建议:
def parallel(l1,l2):
if gradient(l1) != gradient(l2):
return False
return True
Run Code Online (Sandbox Code Playgroud)
可写成
def parallel(l1,l2):
return gradient(l1) == gradient(l2)
Run Code Online (Sandbox Code Playgroud)
同样的,
if min(xranges) <= x <= max(xranges):
return True
else:
return False
Run Code Online (Sandbox Code Playgroud)
可写成
return min(xranges) <= x <= max(xranges)
Run Code Online (Sandbox Code Playgroud)
尽可能避免使用整数索引,尤其是双级整数索引l1[0][0].
单词或变量名比整数索引更容易阅读和理解.
整数索引的一种方法是使用"tuple-unpacking":
(x1, y1), (x2, y2) = l1
Run Code Online (Sandbox Code Playgroud)
然后l1[0][0]成为x1.这可以改善你的代码的可读性gradient和crosses功能.
线条平行时有两种情况.如果线不共线,那么它们永远不会相交.但如果这些线是共线的,它们会在任何地方相交.
这似乎不准确
line_intersection(line, line)
Run Code Online (Sandbox Code Playgroud)
是False线是共线的.似乎更错误(如果这样的事情是可能的:))当有问题的行是完全相同的行时.
如果线是共线的,并且None如果线是平行但非共线,我建议返回任意交点.
当浮点数被比较为平等时,可能会出现一个错误:
In [81]: 1.2 - 1.0 == 0.2
Out[81]: False
Run Code Online (Sandbox Code Playgroud)
这不是Python中的错误,而是由浮点的内部表示引起的问题,它影响以任何语言完成的所有浮点计算.它可以在尝试比较浮点数相等的任何代码中引入一个错误 - 例如:
def parallel(l1,l2):
if gradient(l1) == gradient(l2): ...
Run Code Online (Sandbox Code Playgroud)
因此,不是比较浮点数的相等性,我们可以做的最好的方法是测试两个浮点数是否在某个容差范围内彼此接近.例如,
def near(a, b, rtol=1e-5, atol=1e-8):
# Essentially borrowed from NumPy
return abs(a - b) < (atol + rtol * abs(b))
def parallel(l1,l2):
if near(gradient(l1), gradient(l2)): ...
Run Code Online (Sandbox Code Playgroud)
切勿将字符'l'(小写字母el),'O'(大写字母哦)或'I'(大写字母眼睛)用作单个字符变量名称.
在某些字体中,这些字符与数字1和0无法区分.
而不是l1我的建议line1.
现在,正如@george指出的那样,代码处理垂直线的地方有很多例子(if gradient is None.)如果我们使用线的参数形式,我们可以用同样的方式处理所有线.代码将更简单,因为数学将更简单.
如果你在一条线上知道两点,(x1, y1)和(x2, y2),则该行的参数形式是
l(t) = (x1, y1)*(1-t) + (x2, y2)*t
Run Code Online (Sandbox Code Playgroud)
t标量在哪里.随着t变化,你会得到不同的分数.请注意有关参数形式的一些相关事实:
什么时候t = 1,右手边的第一个词就会消失,所以你就离开了(x2, y2).
当右手边t = 0的第二个任期退出时,你就会离开(x1, y1)*(1-0) = (x1, y1).
等式的右边线性地取决于t.没有t**2术语或任何其他非线性依赖t.因此参数形式描述了一条线.
为什么线的参数形式强大?
线段(x1,y1)到(x2,y2)内的点对应于
t0和1(含)之间的值.所有其他值t
对应于线段外的点.
另请注意,就参数形式而言,垂直线没有什么特别之处.你不必担心无限的斜坡.每条线都可以用同样的方式处理.
我们如何利用这一事实呢?
如果我们有两条参数形式的线:
l1(t) = (x1, y1)*(1-t) + (x2, y2)*t
l2(s) = (u1, v1)*(1-s) + (u2, v2)*s
Run Code Online (Sandbox Code Playgroud)
(将x1,y1,x2,y2,u1,v1,u2,v2视为给定常数),然后线相交
l1(t) = l2(s)
Run Code Online (Sandbox Code Playgroud)
现在,l1(t)是一个二维点.l1(t) = l2(s)是一个二维方程.x-coordinate有一个等式,y内置了-coordinate的等式l1(t) = l2(s).所以我们确实有两个方程,两个未知数(t和s).我们可以解决这些方程式t和s!(希望,如果线不相交,则存在对没有解决方案t和s.
所以让我们做一些数学:)
l1(t) = (x1, y1) + (x2-x1, y2-y1)*t
l2(s) = (u1, v1) + (u2-u1, v2-v1)*s
Run Code Online (Sandbox Code Playgroud)
l1(t) = l2(s) 暗示两个标量方程:
x1 + (x2-x1)*t = u1 + (u2-u1)*s
y1 + (y2-y1)*t = v1 + (v2-v1)*s
(x2-x1)*t - (u2-u1)*s = u1-x1
(y2-y1)*t - (v2-v1)*s = v1-y1
Run Code Online (Sandbox Code Playgroud)
我们可以将其重写为矩阵方程式:

使用克莱默规则,我们可以解决t和s:如果

然后


请注意,Cramer的规则从数学的角度来看是有效的(并且易于编码),但它具有较差的数值属性(另请参阅GEPP与Cramer规则).对于严重的应用程序,请使用LU分解或LAPACK(可通过NumPy获得).
所以我们可以按如下方式编写代码:
def line_intersection(line1, line2):
"""
Return the coordinates of a point of intersection given two lines.
Return None if the lines are parallel, but non-collinear.
Return an arbitrary point of intersection if the lines are collinear.
Parameters:
line1 and line2: lines given by 2 points (a 2-tuple of (x,y)-coords).
"""
(x1,y1), (x2,y2) = line1
(u1,v1), (u2,v2) = line2
(a,b), (c,d) = (x2-x1, u1-u2), (y2-y1, v1-v2)
e, f = u1-x1, v1-y1
# Solve ((a,b), (c,d)) * (t,s) = (e,f)
denom = float(a*d - b*c)
if near(denom, 0):
# parallel
# If collinear, the equation is solvable with t = 0.
# When t=0, s would have to equal e/b and f/d
if near(float(e)/b, float(f)/d):
# collinear
px = x1
py = y1
else:
return None
else:
t = (e*d - b*f)/denom
# s = (a*f - e*c)/denom
px = x1 + t*(x2-x1)
py = y1 + t*(y2-y1)
return px, py
def crosses(line1, line2):
"""
Return True if line segment line1 intersects line segment line2 and
line1 and line2 are not parallel.
"""
(x1,y1), (x2,y2) = line1
(u1,v1), (u2,v2) = line2
(a,b), (c,d) = (x2-x1, u1-u2), (y2-y1, v1-v2)
e, f = u1-x1, v1-y1
denom = float(a*d - b*c)
if near(denom, 0):
# parallel
return False
else:
t = (e*d - b*f)/denom
s = (a*f - e*c)/denom
# When 0<=t<=1 and 0<=s<=1 the point of intersection occurs within the
# line segments
return 0<=t<=1 and 0<=s<=1
def near(a, b, rtol=1e-5, atol=1e-8):
return abs(a - b) < (atol + rtol * abs(b))
line1 = ((4,4),(10,10))
line2 = ((11,5),(5,11))
line3 = ((11,5),(9,7))
line4 = ((4,0),(10,6))
assert all(near(a,b) for a,b in zip(line_intersection(line1,line2), (8.0, 8.0)))
assert all(near(a,b) for a,b in zip(line_intersection(line1,line3), (8.0, 8.0)))
assert all(near(a,b) for a,b in zip(line_intersection(line2,line3), (11, 5)))
assert line_intersection(line1, line4) == None # parallel, non-collinear
assert crosses(line1,line2) == True
assert crosses(line2,line3) == False
Run Code Online (Sandbox Code Playgroud)