IndexError:索引3超出轴0的大小为3的范围

时间:2018-02-13 00:04:11

标签: python list indexoutofboundsexception

所以这是我绘制Bézier曲线的代码:

def bezier(a):
    n = np.shape(a)[0]-1
        # initialise arrays
    B = np.zeros([101, 2])
    terms = np.zeros([n+1, 2])
        # create an array of values for t from 0 to 1 in 101 steps
    t = np.linspace(0, 1, 101)
        # loop through all t values
    for i in range(0, 101):
            #calculate terms inside sum in equation 13
            for j in range(0, n + 1):
                # YOUR CODE HERE
                terms[j,:] = ((1 - t[i]) ** 3 * a[0,:] \
                           + 3 * t[i] * (1-t[i]) ** 2 * a[1,:] \
                           + 3 * t[i] ** 2 * (1-t[i]) * a[2,:] 
                           + t[i] ** 3 * a[3,:])
        #sum terms to find Bezier curve
    B[i, :] = sum(terms, 0)
        # plot Bezier
    pl.plot(B[:, 0], B[:, 1])
        # plot control points
    pl.plot(a[:, 0], a[:, 1],'ko')
        # plot control polygon
    pl.plot(a[:, 0], a[:, 1],'k')
    return B 

当我试图传递一些控制点时:

a = np.array([[0, 0], [0.5, 1], [1, 0]])
B = bezier(a)

我收到这个IndexError:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-16-fce87c9f1c04> in <module>()
      1 a = np.array([[0, 0], [0.5, 1], [1, 0]])
----> 2 B = bezier(a)

<ipython-input-13-3bb3bb02cc87> in bezier(a)
     11            for j in range(0, n + 1):
     12                # YOUR CODE HERE
---> 13                terms[j,:] = ((1 - t[i]) ** 3 * a[0,:] + 3 * t[i] * (1-t[i]) ** 2 * a[1,:] + 3 * t[i] ** 2 * (1-t[i]) * a[2,:] + t[i] ** 3 * a[3,:])
     14        #sum terms to find Bezier curve
     15    B[i, :] = sum(terms, 0)

IndexError: index 3 is out of bounds for axis 0 with size 3

所以我认为它试图访问容器外的东西但是我看不到它需要更改代码的位置。

1 个答案:

答案 0 :(得分:0)

数组a = np.array([[0, 0], [0.5, 1], [1, 0]]没有带索引3的元素。向数组添加另一个点。无论如何,Bezier曲线需要四个点。