The range used in your loop for k in range( 3, tf )
is extrapolating the limit of your Numpy Array x
already in the first iteration.
Your Numpy Array was initialized with only 3 elements:
x = 2 *(np.ones((3,1)))
The first iteration of your for
the index k
is 3
making your equation try to access a fourth element outside the boundaries of your array:
x[k] # Mesmo que x[3]
The solution is to make your interval start from index 2:
for k in range( 2, tf )
Follows 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)
List solution built-in
:
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 save the list x
in a file called saida.txt
just do something like:
with open( 'saida.txt', 'w' ) as arq:
for n in x:
arq.write( str(n) + '\n' )
It is displaying an index error. index 3 is out of bounds for axis 0 with size 3
– Jully Lizandra