index 4 is out of bounds for axis 1 with size 4 Code with Double Sum

Shaun picture Shaun · Nov 14, 2016 · Viewed 45.1k times · Source

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?

Answer

pdowling picture pdowling · Nov 14, 2016

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:

  • The first axis (0) is the index of the selected row (0 to 5)
  • the second axis indexes the column, i.e. the value inside a row (indexed 0 to 4)

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