---
author:
- "[Eugeniy E. Mikhailov](http://physics.wm.edu/~evmik/) and [Greg
  Bentsen](https://physics.wm.edu/~gbentsen/)"
title: Ordinary Differential equations
---

## Today

Ordinary Differential equations

-   Formulation of the problem
-   high order to 1st order transformation
-   Euler method for numerical solution

## n-th order ODE definitions

::: definition
An ordinary equation of order n has the following form

$$y^{(n)} = f(x,y,y', y'', \cdots, y^{(n-1)})$$

$x$
:   independent variable

$y^{(i)}=\frac{\partial^i y}{\partial x^i}$
:   the $i_{th}$ derivative of $y(x)$

$f$
:   the force term
:::

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

## First order ODE example

$$y^{(n)} = f(x,y,y', y'', \cdots, y^{(n-1)})$$

::: example
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) = \frac{dv}{dt} = v'(t) = \frac{F}{m}$$

$t$
:   $\to x$ independent variable

$v$
:   $\to y$

$F/m$
:   $\to f$

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

## n$_{th}$ order ODE transformation to the system of first order ODEs

$$y^{(n)} = f(x,y,y', y'', \cdots, y^{(n-1)})$$

::: definition
We define the following variables
$y_1 =  y, y_2 =  y', y_3 =  y'', \cdots,  y_n = y^{(n-1)}$
:::

$$\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}$$

::: definition
We can rewrite $n_{th}$ order ODE as a system of first order ODEs
${\vec{y}'}=\vec{f}(x,\vec{y})$
:::

# Cauchy boundary conditions

## Cauchy boundary conditions

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

::: definition
With Cauchy boundary conditions, we specify $\vec{y}(x_0)=\vec{y}_0$
i.e. initial conditions

$$\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)=a$$
`\alert{First}`{=tex}, we need to
`\alert{convert it to the canonical form}`{=tex}: the system of the
first order ODEs.

$t$
:   $\to x$ time as independent variable

$x$
:   $\to y \equiv y_1$ particle position

$v$
:   $\to y' \equiv y_2$ velocity

$a$
:   $\to f$ acceleration as a force term

so $$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 $x_0 \to y_{1_0}$ and velocity $v_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)$$

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

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

However, on a small interval $[x, x+h]$, we can assume that $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) + \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) 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.

``` .python
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

::: columns
::: {.column width="60% "}
Let's solve $$y' = -2 y$$ where $y(0)=-1$

Analytical solution $$y = e^{-2x}$$

``` .python
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")
```
:::

::: {.column width="40%"}
![Solution comparison](./pics/example1.png){width="100%"}
:::
:::

## Stability issues for the numerical solution

::: columns
::: {.column width="60% "}
Let's have a look at the first order ODE $$y'= 3y-4e^{-x}$$ It has the
following analytical solution $$y=C e^{3x} +e^{-x}$$ If the initial
condition $y(0)=1$, then the solution is $$y(x)=e^{-x}$$

``` .python
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+\delta$. Thus, $C \neq 0$ and the numerical solution
diverges.

`\alert{Do not trust the numerical solutions (regardless of a method) without proper consideration!}`{=tex}
:::

::: {.column width="40%"}
![Solution comparison](./pics/example2.png){width="100%"}
:::
:::

## Stability issues for the numerical solution

::: columns
::: {.column width="60% "}
Let's have a look at the first order ODE $$y'= 3y-4e^{-x}$$ It has the
following analytical solution $$y=C e^{3x} +e^{-x}$$ If the initial
condition $y(0)=1$, then the solution is $$y(x)=e^{-x}$$

``` .python
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")
```
:::

::: {.column width="40%"}
![Library solver comparison (same
problem)](./pics/example3.png){width="100%"}
:::
:::

## Multi dimensional Euler's method

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

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

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

$$\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, `\alert{the Euler's method is very imprecise}`{=tex} for a
given $h$ and there are better ways.

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