# Numerical Methods for Ordinary Differential Equations

### Short Topical Videos[edit]

### Reference Materials[edit]

### Need to Review?[edit]

## 1 Numerical Integration Methods

Numerical integration is used to solve ODEs that cannot be solved analytically, generally through discretization of the ODE. Since the conception of the modern computer, numerical integration methods have become an essential tool in the physical sciences and beyond. Here we will describe two of many such methods, along with some sample code.

### The Euler Method

The Euler Method is the simplest numerical integration method, and is most likely the only one you will need to use in C207. Here, we’ll walk through how it works and show some examples of how to implement it. Imagine you have some ODE:

with some initial condition . Now, let’s say we want to determine the value of at some new value of that is close to . We can estimate this by rearranging the ODE above into the following form:

which we can write as:

where is called the "step size.” We can generalize this equation with the following recursive relation:

where the step size is typically set as some constant value. As we will see, smaller step sizes produce more accurate integration results. More precisely, the error is on the order of (i.e., reducing by a factor of two makes the Euler method twice as accurate).

\

Now that we have a simple integration scheme, let’s see how we’d execute this in python. Say our ODE is:

and our initial condition is . We can solve this analytically, but let’s see what we get using the Euler method for different values of .

```
. import numpy as np
. import matplotlib.pyplot as plt
.
. # plot analytic solution
. plt.figure(figsize=(10,4))
. x_analytic = np.linspace(0,5,100)
. y_analytic = np.exp(x_analytic)
. plt.plot(x_analytic, y_analytic, 'k--', label='analytic solution')
.
. # define initial condition and values of h that will be used
. x0 = 0
. y0 = 1
. h_values = np.array([0.1,0.5,1.0])
.
. for h in h_values:
. # define arrays that can be used to record x and y
. x = np.zeros([100])
. x[0] = x0
. y = np.zeros([100])
. y[0] = y0
. # execute integration for current value of h
. for i in range(1, len(y)):
. x[i] = x[i-1] + h
. dydx = y[i-1]
. y[i] = y[i-1] + h*dydx
. # plot curve for current value of h
. plt.plot(np.trim_zeros(x, 'b'), np.trim_zeros(y, 'b'), label='h = '+str(h))
.
. # remainder of plotting routine
. plt.xlabel('x', fontsize=12)
. plt.ylabel('y', fontsize=12)
. plt.xlim([0,7])
. plt.ylim([0,100])
. plt.legend(loc=2, fontsize=12)
. plt.tight_layout()
. plt.show()
```

As we can see, the curve obtained using the Euler method converges to the analytic solution as . Therefore, you must be careful to use a value of small enough to produce realistic results when performing numerical integrations.

\

Since this is an astrophysics course, we will conclude this section with a more relevant example. Let’s calculate the trajectory of a non-relativistic electron in the presence of a magnetic field (for relativistic electrons, see: Synchrotron Radiation). Assume the electron begins at the origin and has an initial velocity of . Also assume a magnetic field with a strength of 1e-4 Gauss that points along the x-axis, or . In this case, we need to apply Euler’s method twice within each iteration of the integration. First, we calculate the new position of the electron given its instantaneous velocity:

and then we calculate the new velocity of the electron given its instantaneous acceleration:

In our code, we will use a step size of 1e-6 seconds and integrate for a total of 0.1 seconds.

```
. import numpy as np
. import matplotlib.pyplot as plt
. from mpl_toolkits import mplot3d
.
. # constants
. c = 3e10 # cm/s
. m = 1e-27 # g
. e = 5e-10 # esu
. h = 1e-6 # s
.
. # magnetic field vector (Gauss)
. Bx, By, Bz = 1e-4, 0, 0
. B = np.array([Bx, By, Bz])
.
. # velocity vector (cm/s)
. vx0, vy0, vz0 = 1e5, 0, 1e5
. v = np.array([vx0, vy0, vz0])
.
. # position vector and trajectory arrays
. x, y, z = np.zeros(100000), np.zeros(100000), np.zeros(100000)
. r = np.array([0.0, 0.0, 0.0])
.
. # integration
. for i in range(1, len(x)):
. # calculate next position given current velocity
. r += h*v
. x[i], y[i], z[i] = r[0], r[1], r[2]
. # calculate next velocity given current acceleration
. a = (e/m) * np.cross(v/c, B)
. v += h*a
.
. # plotting routine
. fig = plt.figure(figsize=(10,4))
. ax = plt.axes(projection='3d')
. ax.plot3D(x, y, z, 'black')
. ax.set_xlabel('x (cm)', fontsize=12, labelpad=10)
. ax.set_ylabel('y (cm)', fontsize=12, labelpad=10)
. ax.set_zlabel('z (cm)', fontsize=12, labelpad=10)
. plt.tight_layout()
. plt.show()
```

### The Runge-Kutta Method

Runge-Kutta (RK) methods are a family of iterative techniques used to solve ODEs numerically. Explicit RK methods stem from the equation:

where:

and where the values of , , , and vary based on the specific method being used.

One variation of this equation is the first-order Euler method, for which we set and . Another popular variation is the fourth-order classical Runge-Kutta method, also known as RK4. The equations for RK4 are the following:

where:

Each of these terms looks at the change in at different places in the space and calculates accordingly. The benefit of using RK4 over the Euler method is that it is much more accurate for larger step sizes. Specifically, the error is on the order of . This means that decreasing the step size by a factor of two makes the integration sixteen times more accurate. This advantage would come into play when running a long simulation that requires step sizes too small for the Euler method to complete it in a reasonable time frame. You won’t need to use RK4 for C207, but it may be useful in your research down the line.