我一直在尝试使用这段代码来绘制 C 曲线(https://en.wikipedia.org/wiki/Lévy_C_curve),但不知何故它一直给我这个错误:
IndexError: list index out of range
但是列表的长度对我来说似乎很好,因为它设置为 n-1,那么为什么这个错误会不断出现?
不久前,当我尝试类似的东西(Sierprinski 三角形)时,我遇到了同样的问题,所以我非常感谢一些帮助。
import matplotlib.pyplot as plt
from math import *
def DrawC(direction, length, n):
"""Drawing the curve."""
if n > 0:
direction = direction + (pi / 4.0)
DrawC(direction, length / sqrt(2.0), n-1)
direction = direction - (pi / 2.0)
DrawC(direction, length / sqrt(2.0), n-1)
else:
x = x_lst[-1] + length * cos(direction)
y = y_lst[-1] + length * sin(direction)
x_lst.append(x)
y_lst.append(y)
n = int(raw_input('Generation of the curve: '))
x_lst = []
y_lst = [-150]
direction = pi / 2
length = 300
DrawC(direction, length, n)
plt.plot(x_lst, y_lst)
plt.title("C-curve")
plt.axis([-350, 350, -350, 350])
plt.show()
raw_input('Push the ENTER key: ')