索引出错。索引0超出轴0的大小为0的范围

时间:2017-09-04 00:58:09

标签: python numpy

当我运行我的代码时,我收到错误

  

IndexError:对于v [0] = v0,索引0超出轴0的范围,第42行的大小为0。

我不熟悉python,也不知道如何调试它。

""" Density at height y """
def rho(rh, y):
rho = rh*math.exp(-y/7249)
return rho

""" Acceleration of skydiver """
def accl(m, g, rho, v, As, Cs, Ap, Cp):
if y[i+1] >= 1200:
    accl = (1/(2*m) * rho(rh, y) * v**2 * As * Cs - g )
else:
    accl = (1/(2*m) * rho(rh, y) * v**2 * (As * Cs + Ap * Cp) - g)
return accl

h0 = 4000 # initial hieght
dt = 0.1 #timestep
n  = int(180/dt)
#lists for displacement, time, and velocities
v= np.array([])
v[0] = v0
t= np.array([])
t[0] = t0
y= np.array([])
y[0] = h0

#calculation of time, velocity and displacement
for i in range(n):
t[i+1] = t[i] + dt
v[i+1] = v[i] + accl(m, g, rho, v[i], As, Cs, Ap, Cp) * dt
y[i+1] = y[i] + v[i+1] * dt
if y[i+1] < 0:
    #ends plot once skydiver has landed
        break
# Plot
plt.plot(t, y, label = 'Position m')
plt.plot(t, v, label = 'Speed m/s')
plt.plot(t, accl, label = 'Acceleration m/s^2', color = 'green')
plt.xlim([t[0], t[-1]])
plt.xlabel("Time (seconds)")
plt.legend()

3 个答案:

答案 0 :(得分:1)

从空列表创建的Numpy数组无法编入索引 - 它们没有任何索引元素。

np.array([]).shape
# (0,)

如果您事先知道v的尺寸,可以使用np.empty()

n = 10
np.empty(n, dtype=float)
# array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

或者,只需使用v初始化v0

v = np.array([v0])

答案 1 :(得分:1)

v= np.array([])
v[0] = v0

这没有意义:你试图将值设置为空数组的第一个元素(没有元素!)。

请改为:v = np.array([v0])

如果你想增长数组,请执行以下操作:

v = []
# whatever logic to grow v like:
for i in range(10):
    v.append(2*i-1)
# now turn it into an np.array:
v = np.array(v)

答案 2 :(得分:1)

v = np.array([])替换为v = np.zeros(n+1)。您无法访问numpy数组中超出其边界的元素。你的声明会创建一个空的numpy数组。

相关问题