-1

我一直在尝试使用这段代码来绘制 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: ')
4

1 回答 1

0

列表x_lst不应开始为空。

x = x_lst[-1] + length * cos(direction)当列表不能为空时,无论您的代码采用什么路径。这是有道理的,因为您正在构建一个点列表,因此例如从[0]for开始x_lst。无论如何,这给了我很好的照片:-)

于 2017-03-02T19:29:56.990 回答