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

0

I have this code in Python, but the following error appears:

  

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

Code:

import numpy as np
import math

A=11
T=(math.pi)/60
tf=15000
u=[]
x=[]
x=2*(np.ones((3,1)))

for i in range(1,tf):
    u = np.append(u,A*math.cos(i*T))
for k in range(3,tf):
    x = np.append(x,(2.1579*x[k]-1.3203*x[k-1]+0.16239*x[k-2]+0.0003416*u[k]+0.0019463*u[k-1])
print(x)
    
asked by anonymous 09.10.2017 / 20:03

1 answer

0

The range used in your for k in range( 3, tf ) loop is extrapolating the limit of your NumPy Array x already in the first iteration.

Your NumPy Array has been initialized with only 3 elements:

x = 2 *(np.ones((3,1)))

The first iteration of your% with% index for is k causing your equation to try to access a fourth element outside the boundaries of its array:

x[k]   # Mesmo que x[3]

The solution is to get your interval starting from index 2:

for k in range( 2, tf )

Follow the solution with NumPy Arrays:

import numpy as np
import math

A = 11
T = (math.pi) / 60
tf = 15000

u = (np.zeros((tf,1)))
x = 2.0 * (np.ones((3,1)))

for i in range( 1, tf ):
    u[i] = A * math.cos(i * T)

for k in range( 2, tf ):
    x = np.append( x, 2.1579 * x[k] - 1.3203 * x[k-1] + 0.16239 * x[k-2] + 0.0003416 * u[k] + 0.0019463 * u[k-1] )

print(x)

Solution with lists 3 :

import math

A = 11
T = (math.pi) / 60
tf = 15000

x = [ 2.0 for i in range( 3 ) ]
u = [ A * math.cos(i * T) for i in range( 1, tf ) ]

for k in range( 2, tf ):
    x.append( 2.1579 * x[k] - 1.3203 * x[k-1] + 0.16239 * x[k-2] + 0.0003416 * u[k] + 0.0019463 * u[k-1] )

print(x)

EDIT:

To write the built-in list to a file named x just do something like:

with open( 'saida.txt', 'w' ) as arq:
    for n in x:
        arq.write( str(n) + '\n' )
    
09.10.2017 / 21:05