-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathag_intersect.py
More file actions
60 lines (45 loc) · 1.61 KB
/
Copy pathag_intersect.py
File metadata and controls
60 lines (45 loc) · 1.61 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from __future__ import print_function
def pp(x):
"""Returns a pretty-print string representation of a number.
A float number is represented by an integer, if it is whole,
and up to two decimal places if it isn't
"""
if isinstance(x, float):
if x.is_integer():
return str(int(x))
else:
return "{0:.2f}".format(x)
return str(x)
class point(object):
"""A point in a two dimensional space"""
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def __repr__(self):
return '(' + pp(self.x) + ', ' + pp(self.y) + ')'
class line(object):
"""A line between two points"""
def __init__(self, src, dst):
self.src = src
self.dst = dst
def __repr__(self):
return '['+ str(self.src) + '-->' + str(self.dst) + ']'
def intersect (l1, l2):
"""Returns a point at which two lines intersect"""
x1, y1 = l1.src.x, l1.src.y
x2, y2 = l1.dst.x, l1.dst.y
x3, y3 = l2.src.x, l2.src.y
x4, y4 = l2.dst.x, l2.dst.y
xnum = ((x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4))
xden = ((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4))
xcoor = xnum / xden
ynum = (x1*y2 - y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4)
yden = (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)
ycoor = ynum / yden
return point(xcoor, ycoor)
if __name__ == '__main__':
l1 = line(point(1, 4), point(5, 8))
l2 = line(point(5, 6), point(3, 8))
l3 = line(point(1, 5), point(5, 8))
print('Intersection of', l1, 'with', l2, 'is', intersect(l1, l2) )
print('Intersection of', l2, 'with', l3, 'is', intersect(l2, l3) )