python 分形图简单分形图代码
时间: 2024-10-11 17:03:54 浏览: 39
Python中有许多库可以生成分形图形,其中最常用的是`matplotlib`和`numpy`配合`turtle`模块。这里是一个简单的例子,我们将创建一个基本的Koch曲线分形图像:
```python
import matplotlib.pyplot as plt
import numpy as np
# Koch曲线函数
def koch_curve(length, iterations):
if iterations == 0:
return [length]
else:
segments = []
for i in range(4):
new_segments = koch_curve(length / 3, iterations - 1)
angle = (i * 90) + 60
segments.extend([
(length / 3, 0),
(new_segments[0][0] + length / 3 * np.cos(angle), new_segments[0][1] + length / 3 * np.sin(angle)),
(new_segments[1][0], new_segments[1][1]),
(new_segments[0][0] - length / 3 * np.cos(angle), new_segments[0][1] - length / 3 * np.sin(angle))
])
return segments
# 绘制Koch曲线
def draw_koch(curve, ax):
x, y = zip(*curve)
ax.plot(x, y)
# 创建一个新的图像
fig, ax = plt.subplots()
ax.set_aspect('equal') # 保持纵横比例一致
# 参数设置
length = 300
iterations = 4
points = koch_curve(length, iterations)
# 绘制
draw_koch(points, ax)
plt.show()
阅读全文