Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Initial Value Problems

Open in Colab

An initial value problem is an ordinary differential equation of the form y′(t)=f(t,y)y'(t) = f(t, y) with y(t0)=y0y(t_0) = y_0, where yy can be a scalar or a vector.

The idea is that you specify the starting point of a system and the rules that govern the system, and let the simulation go from there.

Your Zebra Sanctuary

Let’s say you are really enthusiastic about zebras.

Grevy's Zebra Stallion.jpg

By Rainbirder - Grevy's Zebra Stallion, CC BY-SA 2.0, Link

You decide to start a zebra sanctuary in your backyard. Soon you have a bunch of zebras having a great time eating your grass and shrubbery.

A Growing Problem

Your zebras keep having babies. This is manageable for now, and the baby zebras are cute. However, you’re a bit worried about the number of zebras you’re going to need to feed, and you want to figure out what will happen if you let things go unchecked. Naturally, you decide to write a program to simulate your zebra problem.

Let’s say you have z0z_0 zebras this month. The number of zebra babies that will appear next month is proportional to the current population, so

z1=z0+Δ(z0)z_1 = z_0 + \Delta(z_0)

where Δ(z0)=αz0\Delta(z_0) = \alpha z_0. You estimate α\alpha is about 0.02.

Zebras are not all born on the first day of the month, so it is more natural to let the population change continuously. Over a short time Δt\Delta t (measured in months), about αz(t) Δt\alpha z(t)\, \Delta t zebras are born, so z(t+Δt)≈z(t)+αz(t) Δtz(t + \Delta t) \approx z(t) + \alpha z(t)\, \Delta t. Dividing by Δt\Delta t and letting Δt→0\Delta t \to 0 gives a differential equation

z′(t)=αz(t)z'(t) = \alpha z(t)

whose solution is z(t)=z0eαtz(t) = z_0 e^{\alpha t}.

Now it is time to fire up your Python interpreter. We’ll use solve_ivp in scipy.integrate - this is a high-level wrapper with lots of options for solving initial value problems. The important arguments to provide are:

  • f(t, y) - a Python function that returns the right-hand side of the ODE - this can be a vector-valued function. Note that t comes first; the older scipy.integrate.odeint expects f(y, t), so check the order when you read older code.

  • t_span - a tuple (t0, t1) which gives the start and end times of the simulation

  • y0 - the state of the system at t0

solve_ivp will do a lot of work for you - deciding on a backend algorithm, choosing time steps, etc. You might find it useful to specify t_eval, which gives an array of points to evaluate the function on.

The result sol has the fields sol.t, the times, and sol.y, the solution, with one row for each component of yy and one column for each time. That is why we plot sol.y[0] below.

Things do not look good. There is no way you can afford to feed even 100 zebras while paying tuition at the University of Chicago. Hard choices will need to be made.

A Natural Solution

When posting a “Zebras for sale” ad on craigslist, you see an ad for a family of lions that need a home. You feel bad for the lions, and realize you can use them to solve your zebra problem. However, before committing, you want to make sure the lions won’t eat all the zebras (you just want to keep the population controlled, not exterminated). You read a bit about how lions and zebras might interact and decide to use a Predator-Prey model.

  1. Zebras will continue to have babies at rate α\alpha.

  2. A lion will catch and eat every 100-th zebra it sees. The number of zebras a lion sees depends on the zebra population, we’ll denote the rate at which a lion encounters a single zebra in a month as β\beta.

  3. For every 5 zebras the lions eat, a lion baby is born.

  4. Lions die of old age at a rate of γ\gamma

We’ll use xx to denote the number of lions, and zz for the number of zebras. Now, the amount the zebra population changes every month is Δz(z,x)=αz−β100xz\Delta_z(z,x) = \alpha z - \frac{\beta}{100} x z. The amount the lion population changes every month is Δx(x,z)=β500xz−γx\Delta_x(x,z) = \frac{\beta}{500} x z - \gamma x.

In order to solve this problem, we can use a vector y=[x,z]Ty = [x, z]^T, and the following ODE system:

y0′(t)=β500y0y1−γy0,y1′(t)=αy1−β100y0y1y_0'(t) = \frac{\beta}{500} y_0 y_1 - \gamma y_0, \quad y_1'(t) = \alpha y_1 - \frac{\beta}{100} y_0 y_1

You estimate γ\gamma to be 0.02, and β\beta to be 1.0.

You plan to start with 5 lions and 50 zebras.

Oh no! Soon the zebras will be eaten, and you’ll be left with a pack of hungry lions. You wonder what would happen if you do some landscaping to make it easier for the zebras to hide. Then you might have β=0.3\beta = 0.3.

That looks a bit better - what if we run the simulation for longer?

This seems like a good solution - you install some hiding places for zebras, and give the lions a home. You start charging interested visitors for tours, and open a gift shop. Soon you are able to cover the expenses for the zebra hay. You quit your day job and become a safari guide in your own backyard.

Symbolic Solutions of ODEs

You can use SymPy for symbolic solutions of ODEs. For instance, in our zebra growth problem, we had an ODE of the form

y′(t)=ay(t)y'(t) = a y(t)

We can use SymPy to classify the ODEs and find a symbolic solution (if one exists)

You might recognize some of the above from an ODE class. We see that this ODE is fairly simple, and a variety of methods might be used to solve the equation symbolically.

If you have taken a class on ODEs, hopefully this looks correct. If you don’t remember your ODEs, or haven’t seen them before, try verifying that the solution satisfies y'(t) = a * y(t). SymPy can also do the check: checkodesol substitutes a solution into the equation, and returns True and the simplified residual 0 if the equation is satisfied.

The Logistic Equation

Another ODE is the Logistic equation

y′(t)=y(t)(1−y(t))y'(t) = y(t) (1 - y(t))

This models growth of a population with resource limits.

First, let’s use SymPy to find a symbolic solution

Let’s just set the constant C1C_1 to be 1

Let’s look at solving the ODE with y(0)=0.1y(0) = 0.1. We can pass this into SymPy’s ode.dsolve using the ics keyword. Writing 0.1 as the fraction sym.Rational(1, 10) keeps the answer exact:

now, because we actually solved the IVP, there are no constants to fill in, and we can plot the right hand side of the equation:

Now, let’s solve the IVP numerically using scipy

Exercises

  1. Get an exact expression for the zebra growth IVP using SymPy. What is the worst-case error over the 100-month simulation we conducted?

Euler Method

The (forward) Euler Method is a numerical method for solving Initial Value Problems. The basic idea is to choose a step size h, and iteratively compute approximations yk≈y(tk)y_k \approx y(t_k) at the times tk=t0+kht_k = t_0 + kh, starting from the initial value y0y_0, using

yk+1=yk+hf(tk,yk)y_{k+1} = y_k + h f(t_k, y_k)

Each step follows the tangent line to the solution through (tk,yk)(t_k, y_k) for a time hh. Equivalently, it replaces y′(tk)y'(t_k) in the ODE by the forward difference (yk+1−yk)/h(y_{k+1} - y_k)/h from Differentiation. For the zebra equation z′=αzz' = \alpha z with a step of h=1h = 1 month, forward Euler is exactly the month-by-month model zk+1=zk+αzkz_{k+1} = z_k + \alpha z_k that we started from.

Here’s an example implementation

Let’s use this function to compute the solution to the Logistic equation:

How accurate is this? We found the exact solution y(t)=1/(1+9e−t)y(t) = 1/(1 + 9e^{-t}) with SymPy above. Let’s compare it with forward Euler for a few step sizes.

Halving the step size halves the error, so the error of forward Euler is proportional to hh, so it is a first order method.

Events

You can ask solve_ivp to find the location of events. An event is defined as a function event(t, y), and solve_ivp will find values of t where event(t,y) = 0. For instance, in the zebra growth problem, we might want to find the value of t where the number of zebras reaches 100. We can pass in an event or list of events using the events keyword.

we can access the time at which events occur using the t_events field of the solution

The population reaches 100 when it has doubled, at t=ln⁡2/α≈34.657t = \ln 2/\alpha \approx 34.657 months. solve_ivp finds events by checking the sign of zebra100 after every step. When the sign changes, it locates the root inside the step with a root finder (see Root Finding), applied to an interpolating polynomial of the numerical solution.

If you want to end the simulation when an event occurs, you can set a flag terminal=True. You can also specify a direction flag to only trigger an event when the root of the function goes from negative to positive (direction=1), or positive to negative (direction=-1)

Higher-Order Equations

solve_ivp solves first-order systems y′=f(t,y)y' = f(t, y). An equation with higher derivatives can always be rewritten as a first-order system, by making the lower derivatives into new unknowns. For example, the angle θ\theta of a pendulum of length LL satisfies

θ′′(t)=−gLsin⁡θ(t).\theta''(t) = -\frac{g}{L} \sin \theta(t).

With the angular velocity ω=θ′\omega = \theta' as a second unknown, this becomes the system

θ′=ω,ω′=−gLsin⁡θ\theta' = \omega, \qquad \omega' = -\frac{g}{L} \sin\theta

for y=(θ,ω)y = (\theta, \omega). The initial condition has to give both the starting angle θ(0)\theta(0) and the starting angular velocity ω(0)\omega(0). In general, an equation of order mm becomes a system of mm first-order equations for y,y′,…,y(m−1)y, y', \dots, y^{(m-1)}.

Let’s release the pendulum from rest at a few different angles.

For small angles sin⁡θ≈θ\sin\theta \approx \theta, and the equation becomes the harmonic oscillator θ′′=−(g/L) θ\theta'' = -(g/L)\, \theta, whose period 2πL/g≈2.0062\pi\sqrt{L/g} \approx 2.006 seconds does not depend on the amplitude. Larger swings take longer. We can measure the period with an event: the pendulum passes through θ=0\theta = 0 in the same direction once per period.

The exact period is an integral,

T=4Lg∫0π/2dϕ1−k2sin⁡2ϕ,k=sin⁡θ(0)2,T = 4 \sqrt{\frac{L}{g}} \int_0^{\pi/2} \frac{d\phi}{\sqrt{1 - k^2 \sin^2 \phi}}, \qquad k = \sin\frac{\theta(0)}{2},

(a complete elliptic integral of the first kind), which we can compute numerically with quad from Integration & Quadrature.

Exercises

  1. Write the damped oscillator x′′+2ζx′+x=0x'' + 2\zeta x' + x = 0 as a first-order system, and solve it with x(0)=1x(0) = 1, x′(0)=0x'(0) = 0 for ζ=0.1\zeta = 0.1, 1 and 2. Compare with the exact solutions from SymPy’s dsolve.

  2. The energy E=12ω2−gLcos⁡θE = \frac12 \omega^2 - \frac{g}{L} \cos \theta of the pendulum is constant in time. Solve the pendulum equation with θ(0)=2\theta(0) = 2 and ω(0)=0\omega(0) = 0 for 100 seconds with the default tolerances, and plot E(t)−E(0)E(t) - E(0). What happens when you decrease rtol?

Lorenz attractor and chaos

In 1963 Edward Lorenz derived a simplified model of convection in the atmosphere, a system of three ODEs, and found that its solutions oscillate without ever settling into a repeating pattern.

dxdt=p(y−x)\frac{dx}{dt} = p(y - x)
dydt=−xz+rx−y\frac{dy}{dt} = -xz + rx - y
dzdt=xy−bz\frac{dz}{dt} = xy - bz

We use the parameter values from Lorenz’s paper, p=10p = 10, r=28r = 28 and b=8/3b = 8/3, which are also the defaults in the function below. The args keyword of solve_ivp passes extra arguments to the right-hand side after t and y, which is how we pass the parameters below.

Now let’s compute a second solution whose initial xx is shifted by 10-8. We compute both solutions with a high-order method and tight tolerances, so that the difference between them is caused by the shift and not by numerical error (more on this below).

How long can we trust the computed solution?

The first solution above was computed with the default tolerances rtol=1e-3 and atol=1e-6. The numerical error made in each step is also a small perturbation, and in a chaotic system it grows just like the 10-8 shift. To see how far the computed solution can be trusted, we compare it with a reference solution computed with much tighter tolerances.

Conclusion

The Lorenz solution never settles into a steady state or a periodic orbit. It loops around one lobe, then the other, switching at irregular times, but it stays on a bounded, butterfly-shaped set called the Lorenz attractor. The plots of the two nearby solutions show the defining feature of chaos, or sensitive dependence on initial conditions: two solutions that start 10-8 apart separate roughly exponentially. Numerical errors grow the same way, which is why tightening the tolerance extends the reliable part of a computed solution only slowly.

The same holds for the weather, which is what Lorenz was modeling. Small errors in the measurements of today’s weather grow exponentially, so beyond a horizon of a couple of weeks the weather cannot be forecast in detail, however good the model.