B2.4.4–5 · HL 递归
分形树 · HL 应用
Python · 逐步执行
分形树 · HL 应用
同一绘制规则在更小的尺度上重复,直到深度为零。
Python 实现
1import math2segments = []34def fractal(x, y, length, angle, depth):5 if depth == 0:6 return7 end_x = x + length * math.cos(angle)8 end_y = y - length * math.sin(angle)9 segments.append([x, y, end_x, end_y])10 fractal(end_x, end_y, length * 0.65, angle + 0.5, depth - 1)11 fractal(end_x, end_y, length * 0.65, angle - 0.5, depth - 1) B2.4.4 应用:重点理解自相似性、更小的子问题与终止条件。分支递归代码仅作演示,不属于 B2.4.5 的跟踪要求。math 是 Python 的标准数学模块;角度以弧度表示。segments 记录绘图端点。每条分支产生两条更小的分支。