Predator-Prey Systems
When two populations affect each other, one differential equation becomes a system of two. The Lotka–Volterra predator-prey model is the classic example: it has a conserved quantity, so its solutions cycle forever, and that property makes it a good test of numerical integrators and a good warning for anyone building an ecosystem into a game.
Background: Models for Population Growth for single species, and Numerical Solutions: Euler and RK4 for the solvers used here.
The Lotka–Volterra equations
Let be the prey (say rabbits) and the predators (foxes). Assume that without foxes rabbits grow exponentially, without rabbits foxes die out exponentially, and that encounters, proportional to , hurt rabbits and help foxes:
The system is autonomous ( does not appear on the right), so we can study it in the phase plane: each solution traces a curve , and dividing the equations gives the slope of that curve without :
Equilibria
Setting both right-hand sides to zero: and . The solutions are the extinction point and the coexistence point
Linearising at gives the Jacobian , whose eigenvalues are : purely imaginary, so small deviations circle the equilibrium with period close to . Linearisation alone cannot decide whether a centre is really a centre (a tiny nonlinear effect could make it a slow spiral). The next theorem settles it.
A conserved quantity
Theorem. Along every solution with , the function
is constant. Consequently the orbits are closed curves and the populations are periodic.
Proof. By the chain rule,
is strictly convex with its minimum at , so its level sets are closed loops around that point; a solution stays on one loop and, since it never stops (no other equilibria with ), it goes round and round. ∎
Corollary (averages). Over one period , the average prey is and the average predator is , the equilibrium values. Divide the first equation by : . Integrate over a period; the left side gives , so . The prey average follows the same way.
import numpy as np
from scipy.integrate import solve_ivp
a, b, c, d = 1.0, 0.1, 1.5, 0.075 # equilibrium (20, 10)
def lv(t, s):
x, y = s
return [a * x - b * x * y, -c * y + d * x * y]
V = lambda x, y: d * x - c * np.log(x) + b * y - a * np.log(y)
up = lambda t, s: s[0] - c / d # prey crosses 20 ...
up.direction = 1 # ... going upward
sol = solve_ivp(lv, (0, 40), [10.0, 5.0], rtol=1e-10, atol=1e-10,
dense_output=True, events=up)
for t in (0, 2, 4, 6):
x, y = sol.sol(t)
print(f"t = {t}: prey {x:6.2f}, predators {y:6.2f}, V = {V(x, y):.8f}")
T0, T1 = sol.t_events[0][:2]
ts = np.linspace(T0, T1, 20001)
xs, ys = sol.sol(ts)
print(f"period ≈ {T1 - T0:.4f} (small-oscillation estimate {2*np.pi/np.sqrt(a*c):.4f})")
print(f"averages over one period: prey {np.trapezoid(xs, ts)/(T1-T0):.4f}, "
f"predators {np.trapezoid(ys, ts)/(T1-T0):.4f}")t = 0: prey 10.00, predators 5.00, V = -3.81331555
t = 2: prey 35.31, predators 5.06, V = -3.81331555
t = 4: prey 10.08, predators 17.70, V = -3.81331555
t = 6: prey 13.51, predators 3.60, V = -3.81331555
period ≈ 5.4797 (small-oscillation estimate 5.1302)
averages over one period: prey 20.0000, predators 10.0000
The period is longer than the linear estimate because this orbit is far from the equilibrium; the averages match as the corollary promises.
Integrators and ecosystem simulations
A game or simulation usually advances an ecosystem one frame at a time. The obvious update, explicit Euler, adds a little "energy" on every step: creeps up, the cycles grow, and eventually a population crashes to almost zero and the species goes extinct in your game for purely numerical reasons. A one-line change, using the new prey value when updating the predators (semi-implicit or symplectic Euler, the same trick used for game physics, see Integrators), keeps the orbit bounded.
import math
import matplotlib.pyplot as plt
a, b, c, d = 1.0, 0.1, 1.5, 0.075
V = lambda x, y: d * x - c * math.log(x) + b * y - a * math.log(y)
dt, steps = 0.05, 1200 # 60 time units
def run(semi):
x, y, path = 10.0, 5.0, []
for _ in range(steps):
xn = x + dt * (a * x - b * x * y)
y = y + dt * (-c * y + d * (xn if semi else x) * y)
x = xn
path.append((x, y))
return path
plt.figure(figsize=(6, 4))
for semi, name in ((False, "explicit Euler"), (True, "semi-implicit Euler")):
p = run(semi)
plt.plot(*zip(*p), lw=0.8, label=name)
print(f"{name:20s}: V start {V(10, 5):.4f}, V end {V(*p[-1]):.4f}, "
f"min prey {min(q[0] for q in p):.3f}")
plt.xlabel("prey"); plt.ylabel("predators"); plt.legend(); plt.show()explicit Euler : V start -3.8133, V end 11.2334, min prey 0.000
semi-implicit Euler : V start -3.8133, V end -3.8165, min prey 8.056
With the same step size, explicit Euler drives from −3.81 to about 11.2 and the prey down to (numerically) zero, while the semi-implicit run keeps within 0.004 of its true value.
Tip: For ecosystem mechanics, also clamp populations at a minimum or use integer agents with a seeded RNG. Real game ecosystems are usually agent-based (each rabbit is an entity), and the ODE describes their average behaviour, which is a useful sanity check for tuning.
Beyond the basic model
| Model | Change | Effect |
|---|---|---|
| Logistic prey | instead of | cycles spiral into a stable equilibrium |
| Holling type II | predation (predators get full) | can produce a stable limit cycle |
| Competition | both terms negative: | one species wins or both coexist |
| Three species | food chains | chaos becomes possible |
In software
- Game ecosystems and economies: wildlife simulations, resource-and-consumer loops in strategy games, even player-versus-gold-farmer balance follow Lotka–Volterra-like feedback. Use the averages theorem to predict long-run levels from parameters.
- Testing ODE solvers: is an exact invariant, so its drift measures integration error, like energy drift in physics engines.
- Networks and security: models of worms versus patching, or predators (attackers) and prey (vulnerable hosts), have the same structure. SciPy's ODE tools solve all of them the same way.
Exercises
Exercise 1: Equilibrium
Find the coexistence equilibrium of , .
Answer
Solution
Exercise 2: Small-oscillation period
For the system in Exercise 1, estimate the period of small oscillations around the equilibrium.
Answer
Solution
The Jacobian at is , with eigenvalues , so the period is .
Exercise 3: Volterra's principle
Fishing removes a fraction of both populations per unit time: becomes and becomes . What happens to the average prey and predator levels? Check with and .
Answer
Average prey rises to , average predators fall to .
Solution
By the averages corollary the long-run means are the new equilibrium values. Moderate fishing helps the prey: this was Volterra's explanation of why the share of predatory fish in the Adriatic rose when fishing stopped during World War I.
a, b, c, d, f = 1.0, 0.1, 1.5, 0.075, 0.3
print("before:", (c / d, a / b))
print("after: ", (round((c + f) / d, 6), round((a - f) / b, 6)))before: (20.0, 10.0)
after: (24.0, 7.0)
Exercise 4: Competition equilibria
For the competing-species system , , find all equilibria in the closed first quadrant.
Answer
, , and .
Solution
import sympy as sp
x, y = sp.symbols("x y")
print(sp.solve([x * (2 - x - y), y * (3 - x - 2 * y)], [x, y]))[(0, 0), (0, 3/2), (1, 1), (2, 0)]
Test yourself
In , , where is the coexistence equilibrium?
Why are Lotka–Volterra orbits closed curves rather than spirals?
- The Jacobian has real eigenvalues
- The function is constant along solutions
- Because the equations are linear
- Because solve_ivp uses small steps
A game updates rabbits and foxes with explicit Euler and the cycles keep growing until a species dies out. What is the cheapest fix?
- Use a larger time step
- Update one population using the other's new value (semi-implicit Euler) or use RK4
- Add random noise
- Round populations to integers