【面】计算两直线的交点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def isLineCross(p1, p2, p3, p4):
'''
判断两条线是否相交
'''
ret = min(p1[0] , p2[0]) <= max(p3[0] , p4[0]) and min(p3[0] , p4[0]) <= max(p1[0] , p2[0]) and min(p1[1] , p2[1]) <= max(p3[1] , p4[1]) and min(p3[1] , p4[1]) <= max(p1[1] , p2[1])
return ret

print(isLineCross((1,1), (-1,-1), (-1,1), (1,-1)))
print(isLineCross((-1,-1), (-1,-1), (1,1), (1,-1)))
print(isLineCross((-1,-1), (-1,1), (-1,-1), (1,1)))

def lines_insec(x1, y1, x2, y2, x3, y3, x4, y4):
'''
计算两条线交点
'''
if (x2-x1) == 0: # line1直线斜率不存在时
k1 = None
b1 = 0
else:
k1 = (y2-y1)*1.0/(x2-x1)
b1 = y1*1.0 - x1*k1*1.0

if (x4-x3) == 0: # line2直线斜率不存在时
k2 = None
b2 = 0
else:
k2 = (y4-y3)*1.0/(x4-x3)
b2 = y3*1.0 - x3*k2*1.0

if k1 != None and k2 == None: # line1斜率存在,line2斜率不存在
x = x3*1.0
y = k1*x*1.0+b1*1.0
elif k2 != None and k1 == None: # line1斜率不存在,line2斜率存在
x = x1*1.0
y = k2*x*1.0+b1*1.0
elif k1 == k2: # line1、line2平行时
x = None
y = None
else:
x = (b2-b1)*1.0/(k1-k2)
y = k1*x*1.0+b1*1.0
return [x, y]

print(lines_insec(1, 1, -1, -1, -1, 1, 1, -1))
print(lines_insec(-1, -1, -1, 1, 1, 1, 1, -1))
print(lines_insec(-1, -1, -1, 1, -1, -1, 1, 1))
0%