Reputation: 531
Hi I have the following function which produces an out of bounds error:
import numpy as np
import pylab as plt
import scipy
import math
import sympy as sy
T = sy.Symbol('T')
rho = sy.Symbol('rho')
g_T = [1,T,T**2,T*sy.log(T),T**2*sy.log(T)]
g_rho = [1,rho,rho**2,rho*sy.log(rho),rho**2*sy.log(rho)]
g_T_np = np.asarray(g_T)
g_rho_np = np.asarray(g_rho)
c = np.loadtxt("c_test.txt")
def F(T,rho):
ret = 0
for n in xrange(1,5):
for m in xrange(1,6):
inner= c[n,m]*g_T_np*g_rho_np
ret += inner
return ret
print F(T,rho)
where the .txt file is like this:
-0.529586 -0.000208559 -3.36563E-09 2.29441E-05
2.22722E-06 -0.00014526 -2.48888E-09 1.89488E-05
-6.26662E-05 0.000421028 6.17407E-09 -5.14488E-05
0.09977346 -0.000622051 -8.56485E-09 7.49956E-05
-0.01437627 -9.86754E-05 -1.59808E-09 1.22574E-05
The full error displayed is:
Traceback (most recent call last):File "EOS_test.py", line 38, in <module> print F(T,rho) File "EOS_test.py", line 31, in F inner=c[n,m]*g_T_np*g_rho_np IndexError: index 4 is out of bounds for axis 1 with size 4
How can I solve this error?
Upvotes: 4
Views: 94401
Reputation: 15397
Your problem is in setting your xrange
s.
Python lists (and np arrays) are 0 indexed, so you don't want the indices [1,2,3,4,5] and [1,2,3,4,5,6], but instead want [0,1,2,3,4] and [0,1,2,3,4,5] [0,1,2,3] and [0,1,2,3,4].
Setting up your for loops like this would solve your problem:
for n in xrange(0,4):
for m in xrange(0,5):
Or, you can take advantage of xrange's default starting point, and simply list one parameter:
for n in xrange(4):
for m in xrange(5):
Also, for a "more pythonic" solution, instead of having nested for loops, look up how to iterate over an ndarray. The docs give this example:
it = np.nditer(c, flags=['f_index'])
while not it.finished:
inner= c[it[0]]*g_T_np*g_rho_np
ret += inner
it.iternext()
This avoids the whole issue of needing to know the size of the array you're importing, and is therefore much more robust.
Edit: As pdowling mentioned in his answer, the range numbers should be 4 and 5. I had left 5 and 6 in my aswer, and have now changed that.
Upvotes: 0
Reputation: 500
Numpy uses 0-based indexing. From the looks of it you are indexing the array from 1 (2nd position) to 4 (5th position), which is of course out of bounds for the array you are working with. The same is true for the second axis.
Secondly, you've mixed up your axes:
This should work:
def F(T,rho):
ret = 0
for n in range(5):
for m in range(4):
inner= c[n,m]*g_T_np*g_rho_np
ret += inner
return ret
Upvotes: 5