与春光共舞,独属于开发者们的春日场景是什么样的?
使用 Python 和 matplotlib 库生成一幅樱花分形图案。效果
这段代码使用递归的方式绘制樱花树的枝干,通过调整角度和长度,模拟出分形的效果。代码
import matplotlib.pyplot as plt
import numpy as np
def draw_branch(x, y, angle, length, level):
if level == 0:
return
x_end = x + length * np.cos(np.radians(angle))
y_end = y + length * np.sin(np.radians(angle))
plt.plot([x, x_end], [y, y_end], color='pink', linewidth=1)
# 递归绘制子树
new_length = length * 0.7
draw_branch(x_end, y_end, angle - 30, new_length, level - 1)
draw_branch(x_end, y_end, angle + 30, new_length, level - 1)
# 初始化画布
plt.figure(figsize=(8, 6))
plt.axis('off') # 关闭坐标轴
# 绘制主干
x_start, y_start = 0, 0
draw_branch(x_start, y_start, 90, 10, 7) # 初始角度向上,长度为10,递归7层
# 显示图像
plt.title('春日樱花分形图案')
plt.show()
赞16
踩0