python – IndexError: index out of bounds

python – IndexError: index out of bounds

From a quick look, it seems the problem is the for loop, instead of using for i in [N[0]], are you sure its not for i in range(N[0])?

for i in [N[0]] is rather redundant because the list only contains one element, ie. N[0], so the list of size 800 becomes out of index when you try to seek dydt[800] <– as the max index is 799.

Like so:

In [9]: N
Out[9]: [800, 400, 800]

In [10]: for i in [N[0]]:  # ie. i == N[0] == 800
   ....:     dydt[i] = 0
   ....:     
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-10-04daa45ec403> in <module>()
      1 for i in [N[0]]:  # ie. i == N[0] == 800
----> 2     dydt[i] = 0
      3 

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

In [11]: for i in range(N[0]):
   ....:     dydt[i] = 0
   ....:     
L = [8.0, 4.0, 8.0] 
dN = 1.0e2 
N = [int(l*dN) for l in L] # create array [800, 400, 800] 

dydt = np.zeros(shape=N) # create 3 dimensional matrix 
                         # 1d has size 800 (from 0 to 799 including)
                         # 2d has size 400 (from 0 to 399 including)
                         # 3d same as 1st

In this code:

for i in[N[0]]: 
    dydt[i] = 0 # Unknown point

I is always 800 so it actually same as dydt[ 800 ] = 0. which is bigger then 799.

Its looks like that you use numpy arrays in wrong way.

Yes in low level they represents as contiguous array of ints or floats of whatever. But on python level np.array represents as array of arrays. (ie first element as 3d matrix mtx = np.zeros(shape=[800,400,800] in python will be mtx[0][0][0])).

So all code after for i in[N[0]]: will not work. It tries to access subarray that out of matrix bounds.

UPDATE:

for example you have 3d matrix (3x3x3)

 mtx=np.zero(shape=[3,3,3])
 print(mtx) 
 #[ [ [ 0.  0.  0.]
 #    [ 0.  0.  0.]
 #    [ 0.  0.  0.] ]

 #  [ [ 0.  0.  0.]
 #    [ 0.  0.  0.]
 #    [ 0.  0.  0.] ]

 #  [ [ 0.  0.  0.]
 #    [ 0.  0.  0.]
 #    [ 0.  0.  0.] ] ]

 mtx[0] = 1 
 print( mtx )
 #[ [ [ 1.  1.  1.]
 #    [ 1.  1.  1.]
 #    [ 1.  1.  1.] ]

 #  [ [ 0.  0.  0.]
 #    [ 0.  0.  0.]
 #    [ 0.  0.  0.] ]

 #  [ [ 0.  0.  0.]
 #    [ 0.  0.  0.]
 #    [ 0.  0.  0.] ] ]

 mtx[0][1] = 2
 #[ [ [ 1.  1.  1.]
 #    [ 2.  2.  2.]
 #    [ 1.  1.  1.] ]

 # others are zeros

 mtx[0][1][2] = 3
 #[ [ [ 1.  1.  1.]
 #    [ 2.  2.  3.]
 #    [ 1.  1.  1.] ]

 # others are zeros

python – IndexError: index out of bounds

Leave a Reply

Your email address will not be published.