代码参照科赫曲线博文。递归思路建议读原文增强理解。
import matplotlib.pyplot as plt
import math
# 原文链接:https://blog.csdn.net/qq_33598125/article/details/88562822
class point:
def _init_(self):
self.x=0
self.y=0
def koch(n,p1,p2,xx,yy):
if n==0:
return
s,t,u=point(),point(),point()
theta=math.pi / 3
s.x=p1.x+(p2.x-p1.x)/3.
s.y=p1.y+(p2.y-p1.y)/3.
t.x=p2.x-(p2.x-p1.x)/3.
t.y = p2.y - (p2.y - p1.y) / 3.
u.x=math.cos(theta)*(t.x-s.x)-math.sin(theta)*(t.y-s.y) +s.x
u.y = math.sin(theta) * (t.x - s.x) + math.cos(theta) * (t.y - s.y) +s.y
koch(n-1,p1,s,xx,yy)
xx.append(s.x)
yy.append(s.y)
koch(n-1,s,u,xx,yy)
xx.append(u.x)
yy.append(u.y)
koch(n-1,u,t,xx,yy)
xx.append(t.x)
yy.append(t.y)
koch(n-1,t,p2,xx,yy)
return xx,yy
p1,p2=point(),point()
p1.x=0
p1.y=0
p2.x=100
p2.y=0
n = int(2)# 调整阶数
xx = []
yy = []
xx.append(p1.x)
yy.append(p1.y)
nxx,nyy = koch(n,p1,p2,xx,yy)
nxx.append(p2.x)
nyy.append(p2.y)
ax = plt.subplot(111)
plotdict = { 'dx': nxx, 'dy': nyy }
ax.plot('dx','dy','b',data=plotdict)
plt.show()
可视化结果:
书籍信息:
题名/责任者:分形几何学/陈颙,陈凌编著
出版发行项:北京:地震出版社,1998
ISBN及定价:7-5028-1482-5/RMB22.00