Ordinary Differential equations

Eugeniy E. Mikhailov and Greg Bentsen

Today

Ordinary Differential equations

n-th order ODE definitions

An ordinary equation of order n has the following form

y(n)=f(x,y,y′,y″,⋯,y(n−1))y^{(n)} = f(x,y,y', y'', \cdots, y^{(n-1)})

xx
independent variable
y(i)=∂iy∂xiy^{(i)}=\frac{\partial^i y}{\partial x^i}
the ithi_{th} derivative of y(x)y(x)
ff
the force term

Unfortunately, mathematicians use xx as independent variable. For a physicist a more natural choice would be tt since everything depends on time.

First order ODE example

y(n)=f(x,y,y′,y″,⋯,y(n−1))y^{(n)} = f(x,y,y', y'', \cdots, y^{(n-1)})

The acceleration of a body is the first derivative of velocity with respect to the time and equals to the force divided by mass a(t)=dvdt=v′(t)=Fma(t) = \frac{dv}{dt} = v'(t) = \frac{F}{m}

tt
→x\to x independent variable
vv
→y\to y
F/mF/m
→f\to f

And we obtain the canonical form y(1)=f(x,y)y^{(1)}= f(x,y) for the first order ODE

nth_{th} order ODE transformation to the system of first order ODEs

y(n)=f(x,y,y′,y″,⋯,y(n−1))y^{(n)} = f(x,y,y', y'', \cdots, y^{(n-1)})

We define the following variables y1=y,y2=y′,y3=y″,⋯,yn=y(n−1)y_1 = y, y_2 = y', y_3 = y'', \cdots, y_n = y^{(n-1)}

(y1′y2′y3′⋮yn−1′yn′)=(f1f2f3⋮fn−1fn)=(y2y3y4⋮ynf(x,y1,y2,y3,⋯yn))\begin{pmatrix} y_1'\\ y_2'\\ y_3'\\ \vdots\\ y_{n-1}'\\ y_n' \end{pmatrix} = \begin{pmatrix} f_1\\ f_2\\ f_3\\ \vdots\\ f_{n-1}\\ f_n \end{pmatrix} = \begin{pmatrix} y_2\\ y_3\\ y_4\\ \vdots\\ y_{n} \\ f(x, y_1, y_2, y_3, \cdots y_n) \end{pmatrix}

We can rewrite nthn_{th} order ODE as a system of first order ODEs y→′=f→(x,y→){\vec{y}'}=\vec{f}(x,\vec{y})

Cauchy boundary conditions

Cauchy boundary conditions

y→′=f→(x,y→){\vec{y}'}=\vec{f}(x,\vec{y}) This is the system of nn equations and thus requires nn constraints.

With Cauchy boundary conditions, we specify y→(x0)=y→0\vec{y}(x_0)=\vec{y}_0 i.e. initial conditions

(y1(x0)y2(x0)y3(x0)⋮yn(x0))=(y10y20y30⋮yn0)=(y0y0′y0″⋮y0(n−1))\begin{pmatrix} y_1(x_0)\\ y_2(x_0)\\ y_3(x_0)\\ \vdots\\ y_n(x_0) \end{pmatrix} = \begin{pmatrix} y_{1_0}\\ y_{2_0}\\ y_{3_0}\\ \vdots\\ y_{n_0} \end{pmatrix} = \begin{pmatrix} y_0\\ y_0'\\ y_0''\\ \vdots\\ y_0^{(n-1)} \end{pmatrix}

Problem example

If acceleration of the particle is given, then we find the position of the particle as a function of time by solving x″(t)=ax''(t)=a First, we need to convert it to the canonical form: the system of the first order ODEs.

tt
→x\to x time as independent variable
xx
→y≡y1\to y \equiv y_1 particle position
vv
→y′≡y2\to y' \equiv y_2 velocity
aa
→f\to f acceleration as a force term

so x″=a→y″=f→y→′=f→(x,y→)→(y1′y2′)=(y2f)x''=a \to y'' = f \to \vec{y}'=\vec{f}(x,\vec{y}) \to \begin{pmatrix} y_1'\\ y_2' \end{pmatrix} = \begin{pmatrix} y_2\\ f \end{pmatrix}

We also need to provide the initial conditions:
position x0→y10x_0 \to y_{1_0} and velocity v0→y20v_0 \to y_{2_0}

Euler’s method

Let’s, for simplicity, consider a simple first order ODE (notice the lack of the vector notation) y′=f(x,y)y'=f(x,y)

There is an exact way to write the solution y(xf)=y(x0)+∫x0xff(x,y)dxy(x_f)= y(x_0) + \int_{x_0}^{x_f} f(x,y) dx

The problem is that f(x,y)f(x,y) depends on yy itself.

However, on a small interval [x,x+h][x, x+h], we can assume that f(x,y)f(x,y) is constant.

Then, we can use the familiar box integration formula. In application to the ODE, this is called the Euler’s method.

y(x+h)=y(x)+∫xx+hf(x,y(x))dx≈y(x)+f(x,y(x))hy(x+h) = y(x) + \int_{x}^{x+h} f(x,y(x)) dx \approx y(x) + f(x,y(x)) h

Euler’s method implementation

y(x+h)=y(x)+f(x,y)hy(x+h) = y(x) + f(x,y) h

Prompt

Using python write Euler method of ODE solver, follow ‘solve-ivp’ specs for fun, t_span, and y0. Save outcomes to this dir in file ‘euler.py’

We need to replace “time” with x variable to convert it to math notation.

import numpy as np

def euler_method(f, x_span, y0, num_steps):
    """
    Solve an initial value problem using the Euler method.
    
    Parameters:
    f: callable, the derivative function dy/dx = f(x, y)
    x_span: tuple, (x0, xf) the initial and final x points
    y0: array-like, initial condition
    num_steps: int, number of steps to take
    
    Returns:
    x: array of x points
    y: array of solution values at each x point
    """
    x0, xf = x_span
    dx = (xf - x0) / num_steps
    x = np.linspace(x0, xf, num_steps + 1)
    y = np.zeros((num_steps + 1, len(y0)))
    y[0] = y0
    
    for i in range(num_steps):
        y[i+1] = y[i] + dx * f(x[i], y[i])
    
    return x, y

ODE example

Let’s solve y′=−2yy' = -2 y where y(0)=−1y(0)=-1

Analytical solution y=e−2xy = e^{-2x}

import numpy as np
import matplotlib.pyplot as plt
from euler import euler_method

def example1_ode(x, y):
    return -2 * y # Example: dy/dx = -2y, y(0) = 1

x_span = (0, 2)
y0 = [1]
num_steps = 100

x, y = euler_method(example1_ode, x_span, y0, num_steps)
plt.plot(x,y, label="Euler's method")
plt.plot(x,np.exp(-2*x), label="Analytical solution")
plt.title("Solution of y'=-2y, y(0)=1")
plt.legend()
plt.savefig("../pics/example1.png")
Solution comparison
Solution comparison

Stability issues for the numerical solution

Let’s have a look at the first order ODE y′=3y−4e−xy'= 3y-4e^{-x} It has the following analytical solution y=Ce3x+e−xy=C e^{3x} +e^{-x} If the initial condition y(0)=1y(0)=1, then the solution is y(x)=e−xy(x)=e^{-x}

import numpy as np
import matplotlib.pyplot as plt
from euler import euler_method

def example2_ode(x, y):
    return 3 * y - 4*np.exp(-x) # Example: dy/dx = 3y - 4*exp(-x), y(0) = 1

x_span = (0, 2)
y0 = [1]
num_steps = 100

x, y = euler_method(example2_ode, x_span, y0, num_steps)
plt.plot(x,y, label="Euler's method")
plt.plot(x,np.exp(-x), label="Analytical solution, exp(-x)")
plt.title("Solution of y'=3y-4*exp(-x), y(0)=1")
plt.legend()
plt.savefig("../pics/example2.png")

It is clear that the numerical solution diverges from the analytical solution. The problem is in the round off errors. From a computer point of view, y(0)=1+δy(0)=1+\delta. Thus, C≠0C \neq 0 and the numerical solution diverges.

Do not trust the numerical solutions (regardless of a method) without proper consideration!

Solution comparison
Solution comparison

Stability issues for the numerical solution

Let’s have a look at the first order ODE y′=3y−4e−xy'= 3y-4e^{-x} It has the following analytical solution y=Ce3x+e−xy=C e^{3x} +e^{-x} If the initial condition y(0)=1y(0)=1, then the solution is y(x)=e−xy(x)=e^{-x}

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp

def example2_ode(x, y):
    return 3 * y - 4*np.exp(-x) # Example: dy/dx = 3y - 4*exp(-x), y(0) = 1

x_span = (0, 2)
y0 = [1]
num_steps = 100

sol = solve_ivp(example2_ode, x_span, y0, t_eval=np.linspace(x_span[0], x_span[1], num_steps),  method='RK45')
x = sol.t  # note t !!!
y = sol.y 

plt.plot(x.reshape([num_steps,1]),y.reshape([num_steps,1]), label="Runge-Kutta method of order 5(4)")
plt.plot(x,np.exp(-x), label="Analytical solution, exp(-x)")
plt.title("Solution of y'=3y-4*exp(-x), y(0)=1")
plt.legend()
plt.savefig("../pics/example3.png")
Library solver comparison (same problem)
Library solver comparison (same problem)

Multi dimensional Euler’s method

y(x+h)=y(x)+f(x,y)hy(x+h) = y(x) + f(x,y) h

All we need is to split our interval into a bunch of steps of the size hh and leap frog from the first x0x_0 to the next one x0+hx_0+h, then to the x0+2hx_0+2h, and so on.

Now, we can make an easy transformation to the vector case (i.e. the nthn_{th} order ODE)

y→(x+h)=y→(x)+f→(x,y)h\vec{y}(x+h) = \vec{y}(x) + \vec{f}(x,y) h

Similarly to the boxes integration method, which is inferior in comparison to more advance methods, for example, the trapezoidal and Simpson’s, the Euler's method is very imprecise for a given hh and there are better ways.

Most notable improvements are the Runge-Kutta methods of 2nd and 4th order.