sam shen
sam shen

Reputation: 11

Error with index. index 0 is out of bounds for axis 0 with size 0

When I run my code I get the error

IndexError: index 0 is out of bounds for axis 0 with size 0 on line 42 for v[0]=v0.

I'm not familiar with python and don't know how to debug this.

""" 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()

Upvotes: 0

Views: 10732

Answers (3)

bkr879
bkr879

Reputation: 2105

Replace v = np.array([]) with v = np.zeros(n+1). Your cannot access elements of the numpy array that are outside of its bounds. Your declaration creates an empty numpy array.

Upvotes: 1

Julien
Julien

Reputation: 15070

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

This makes no sense: you are trying to set a value to the first element of an empty array (which has no element!).

Try this instead: v = np.array([v0])

if you want to grow your array, do this:

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)

Upvotes: 1

andrew_reece
andrew_reece

Reputation: 21264

Numpy arrays created from empty lists can't be indexed - they don't have any elements to index into.

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

If you know the dimensions of v in advance, you can use np.empty():

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

Alternately, just initialize v with v0:

v = np.array([v0])

Upvotes: 1

Related Questions