[python] IndexError: index 1 is out of bounds for axis 0 with size 1/ForwardEuler

I am numerically solving for x(t) for a system of first order differential equations. The system is:

dy/dt=(C)\*[(-K\*x)+M*A]

I have implemented the Forward Euler method to solve this problem as follows: Here is my code:

import matplotlib
import numpy as np
from numpy import *
from numpy import linspace
from matplotlib import pyplot as plt


C=3
K=5
M=2
A=5
#------------------------------------------------------------------------------
def euler (f,x0,t):
    n=len (t)
    x=np.array ([x0*n])
    for i in xrange (n-1):
        x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
    return x



#---------------------------------------------------------------------------------          
if __name__=="__main__":
    from pylab import *

    def f(x,t): 
        return (C)*[(-K*x)+M*A]

    a,b=(0.0,10.0)
    n=200
    x0=-1.0
    t=linspace (a,b,n)

    #numerical solutions
    x_euler=euler(f,x0,t)

    #compute true solution values in equal spaced and unequally spaced cases
    x=-C*K
    #figure
    plt.plot (t,x_euler, "b")
    xlabel ()
    ylabel ()
    legend ("Euler")

    show()
`
M=2
A=5
#----------------------------------------------------------------------------
def euler (f,x0,t):
    n=len (t)
    x=np.array ([x0*n])
    for i in xrange (n-1):
        x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
    return x



#---------------------------------------------------------------------------          
if __name__=="__main__":
    from pylab import *

    def f(x,t): 
        return (C)*[(-K*x)+M*A]

    a,b=(0.0,10.0)
    n=200
    x0=-1.0
    t=linspace (a,b,n)

    #numerical solutions
    x_euler=euler(f,x0,t)

    #compute true solution values in equal spaced and unequally spaced cases
    x=-C*K
    #figure
    plt.plot (t,x_euler, "b")
    xlabel ()
    ylabel ()
    legend ("Euler")

    show()

I get following Traceback:

Traceback (most recent call last):
  File "C:/Python27/testeuler.py", line 50, in <module>
    x_euler=euler(f,x0,t)
  File "C:/Python27/testeuler.py", line 28, in euler
    x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
IndexError: index 1 is out of bounds for axis 0 with size 1

I don´t understand what is probably wrong.I already looked up after solved questions, but it doesn´t help me along.Can you find my error? I am using following code as an orientation: def euler( f, x0, t ):

    n = len( t )
    x = numpy.array( [x0] * n )
    for i in xrange( n - 1 ):
        x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )

    return x
if __name__ == "__main__":
    from pylab import *

    def f( x, t ):
        return x * numpy.sin( t )

    a, b = ( 0.0, 10.0 )
    x0 = -1.0

    n = 51
    t = numpy.linspace( a, b, n )

    x_euler = euler( f, x0, t )

My goal is to plot the function.

This question is related to python function python-2.7

The answer is


The problem, as the Traceback says, comes from the line x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ). Let's replace it in its context:

  • x is an array equal to [x0 * n], so its length is 1
  • you're iterating from 0 to n-2 (n doesn't matter here), and i is the index. In the beginning, everything is ok (here there's no beginning apparently... :( ), but as soon as i + 1 >= len(x) <=> i >= 0, the element x[i+1] doesn't exist. Here, this element doesn't exist since the beginning of the for loop.

To solve this, you must replace x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ) by x.append(x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )).


The problem is with your line

x=np.array ([x0*n])

Here you define x as a single-item array of -200.0. You could do this:

x=np.array ([x0,]*n)

or this:

x=np.zeros((n,)) + x0

Note: your imports are quite confused. You import numpy modules three times in the header, and then later import pylab (that already contains all numpy modules). If you want to go easy, with one single

from pylab import *

line in the top you could use all the modules you need.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to python-2.7

Numpy, multiply array with scalar Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION] How to create a new text file using Python Could not find a version that satisfies the requirement tensorflow Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Display/Print one column from a DataFrame of Series in Pandas How to calculate 1st and 3rd quartiles? How can I read pdf in python? How to completely uninstall python 2.7.13 on Ubuntu 16.04 Check key exist in python dict