equal
deleted
inserted
replaced
|
1 import pylab as P |
|
2 |
|
3 def split_line(pt1, pt2): |
|
4 """Given two complex numbers p1 and p2 return a list of the |
|
5 necessary points pairwise. |
|
6 """ |
|
7 # The points we generate are p1, p2, p3, p4 and p5 |
|
8 p1, p5 = pt1, pt2 |
|
9 diff = pt2 - pt1 |
|
10 segment = diff/3.0 |
|
11 p2 = p1 + segment |
|
12 p4 = p5 - segment |
|
13 # Now rotate a line given by 60degrees. |
|
14 # Recall that complex multiplication does this easily. |
|
15 # Complex numbers are defined by complex(a, b) also. |
|
16 p3 = p2 + segment*complex(P.cos(P.pi/3), P.sin(P.pi/3)) |
|
17 return [(p1, p2), (p2, p3), (p3, p4), (p4, p5)] |
|
18 |
|
19 def koch(n): |
|
20 start = complex(0, 0) |
|
21 end = complex(1, 0) |
|
22 points = [(start, end)] |
|
23 for level in range(n): |
|
24 new_points = [] |
|
25 for (p1, p2) in points: |
|
26 new_points.extend(split_line(p1, p2)) |
|
27 points = new_points |
|
28 points.insert(0, (start, points[0][0]) ) |
|
29 points.append((points[-1][1], end)) |
|
30 return points |
|
31 |
|
32 def plot_koch(n): |
|
33 points = koch(n) |
|
34 x = [t[0].real for t in points] |
|
35 y = [t[0].imag for t in points] |
|
36 |
|
37 P.plot(x, y, 'r-') |
|
38 P.ylim(0, 1) |
|
39 P.xlim(0, 1) |
|
40 |