Python Code for Euler Method

You can copy and paste this code into Python. If you don’t have Python on your computer you can find a free online Python compiler by doing a web serach.

# Euler Method for 2nd order ODE's

# This Python program solves this example
# ODE x'' + t x' + 6x = 0  
# IC x(0) =3 and x'(0) = 2
# Use time step of Delta_t = 0.2 to approximate x(0.6) and x'(0.6).

#Note. For this example, the tangent vector T = (v, -t*v - 6*x, 1)

#-------------------- 
import numpy as np # only needed if you want to access functions like sin exp etc. 
#-------------------- 
def vdot(x,v):
    return -t*v - 6*x   # put dv/dt from the tangent vector T here 

t0 = 0  # put the initial conditions here
x0 = 3
v0 = 2

tf = 0.6  # put the final time tf at which you want to estimate x and v
dt = 0.2  # put Delta t time step here
#---------------------
# You don't need to change anything below here
#---------------------
n = round( (tf - t0)/dt )
t_vals = [t0]
x_vals = [x0]
v_vals = [v0]
t, x, v = t0, x0, v0
#---------------------
for _ in range(n):
    xnew = x + (v)*dt
    vnew = v + (vdot(x,v))*dt
    tnew = round(t + 1*dt,5)
    x_vals.append(xnew)
    v_vals.append(vnew)
    t_vals.append(tnew)
    t, x, v = tnew, xnew, vnew
#---------------------
print('Euler Points are of the form  [x_n, v_n, t_n] ')
for i in range(n+1):
    print('The n = ', i, ' Euler Point  is ', '[', x_vals[i], ',', v_vals[i],',', t_vals[i], ']')
#--------------------- End of Python Code


    

The output should be something like:

Euler Points are of the form [x_n, v_n, t_n]
The n = 0 Euler Point is [ 3 , 2 , 0 ]
The n = 1 Euler Point is [ 3.4 , -1.6 , 0.2 ]
The n = 2 Euler Point is [ 3.08 , -5.616 , 0.4 ]
The n = 3 Euler Point is [ 1.9568 , -8.86272 , 0.6 ]