写一个Python随机树的代码
以下是一个简单的随机树代码示例,其中使用了numpy和matplotlib库。该代码使用递归方法生成随机树。每个节点都有一个随机的子节点数量和角度。树的深度和分支数量可以通过调整变量来更改。
import numpy as np
import matplotlib.pyplot as plt
# 定义随机树类
class RandomTree:
def __init__(self, depth, branches, angle):
self.depth = depth
self.branches = branches
self.angle = angle
def draw(self, start_pos, length, angle):
# 计算终点坐标
end_pos = start_pos + length * np.array([np.cos(angle), np.sin(angle)])
# 绘制线段
plt.plot([start_pos[0], end_pos[0]], [start_pos[1], end_pos[1]], color='black')
# 递归生成子节点
if self.depth > 0:
for i in range(self.branches):
new_angle = angle + (i - self.branches/2) * self.angle
child = RandomTree(self.depth-1, self.branches, self.angle)
child.draw(end_pos, length * 0.7, new_angle)
# 创建随机树对象并绘制
tree = RandomTree(5, 3, np.pi/4)
plt.figure(figsize=(8, 8))
plt.axis('equal')
tree.draw(np.array([0,0]), 1, -np.pi/2)
plt.show()
在上面的代码中,我们创建了一个名为RandomTree的类,它包含三个属性:深度,分支数量和角度。我们还定义了一个名为draw的方法,该方法使用matplotlib库绘制随机树。
在draw方法中,我们首先计算终点坐标,然后使用plot函数绘制线段。接下来,我们使用递归方法生成子节点。在递归调用中,我们使用相同的draw方法生成子节点,但是深度减少1,长度缩小为原来的0.7,并且角度增加或减少self.angle。
最后,我们创建了一个名为tree的RandomTree对象,并使用draw方法绘制了它。我们还使用plt.figure函数设置了绘图大小,并使用plt.axis('equal')使x轴和y轴的比例相等。最后,我们调用plt.show()函数显示图形。
原文地址: https://www.cveoy.top/t/topic/ArN 著作权归作者所有。请勿转载和采集!