Euler’s Method

The simplest numerical method for approximating solutions of differential equations is Euler’s method. In fact it is just another technique used to analyze a Differential Equation, which uses the idea of local linearity or linear approximation, where we use small tangent lines over a short distance to approximate the solution to an initial-value problem.

The Formula for Euler’s Method:

Euler’s Approximation

Implementation

Let’s write a function called odeEuler which takes 3 input parameters f, y0 and t where:

  • f is a function of 2 variables which represents the right side of a first order differential equation y’ = f(y,t)
  • t is a 1D NumPy array of values where we are approximating values
  • y0 is an intial value where is the entry at index 0 of the array t

The function odeEuler returns a 1D NumPy array of values which approximate the solution of the differential equation

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

def odeEuler(f,y0,t):
'''Approximate the solution of y'=f(y,t) by Euler's method.

Parameters
----------
f : function
    Right-hand side of the differential equation y'=f(t,y), y(t_0)=y_0
y0 : number
    Initial value y(t0)=y0 wher t0 is the entry at index 0 in the array t
t : array
    1D NumPy array of t values where we approximate y values. Time step
    at each iteration is given by t[n+1] - t[n].

Returns
-------
y : 1D NumPy array
    Approximation y[n] of the solution y(t_n) computed by Euler's method.
'''
y = np.zeros(len(t))
y[0] = y0
for n in range(0,len(t)-1):
    y[n+1] = y[n] + f(y[n],t[n])*(t[n+1] - t[n])
return y

t = np.linspace(0,2,21)
y0 = 1
f = lambda y,t: y
y = odeEuler(f,y0,t)
y_true = np.exp(t)
plt.plot(t,y,'b.-',t,y_true,'r-')
plt.legend(['Euler','True'])
plt.axis([0,2,0,9])
plt.grid(True)
plt.title("Solution of $y'=y , y(0)=1$")
plt.show()

Non-Linear Equation

t = np.linspace(0,5,16)
y0 = -1
f = lambda y,t: y**2
y = odeEuler(f,y0,t)
t_true = np.linspace(0,5,100)
y_true = -1/(t_true + 1)
plt.plot(t,y,'r.-',t_true,y_true)
plt.legend(['Euler','True'])
plt.grid(True)
plt.axis([0,5,-1,0])
plt.title("Solution of $y'=y^2 , y(0)=1$")
plt.show()