Modelcore
Logistic map
Also called May logistic map.
The population model x_(t+1) = r x_t (1 - x_t), whose fixed point gives way to cycles of period 2, 4, 8 and then to chaos as r grows, May's example.
The logistic map is the population model for a species with separate, non-overlapping generations. The value is the population in generation as a fraction of a maximum, and is the growth factor per generation at low density. The factor makes the growth fall as the population grows. May (1976) used this map to show that a very simple deterministic model can have very complicated dynamics. As grows from 1 to 4, the population first settles to a fixed level, then to cycles of period 2, 4, 8 and so on, and then changes without a period, in a way that depends sensitively on the start. So erratic numbers in a field census do not prove that the environment is random. The map is also the standard first example of chaos in one dimension.
The machine
The state. One number , the population in generation divided by a scale . The population is . The scale is the population at which the next generation is zero, not the equilibrium level.
The parameter. , with no unit: the number of offspring per individual per generation that survive to breed when the population is small. In the population model .
The update rule. with . In the units of the population, . The slope of the map is .
The assumptions. Generations are discrete and do not overlap, as in many insects with one generation per year. The population is closed, with no migration. The growth per individual falls linearly with the density. The model is deterministic and has no age or space structure. For the map sends into itself, because has its maximum at . For some values go above 1, and then the next population is negative, which has no biological meaning. The Ricker model does not have this defect.
LOGISTIC-MAP(r, x_0, T)- 1
x ← x_0 - 2
for t ← 1 to T do - 3
x ← r x (1 - x) - 4
record x_t ← x - 5
return x_1, ..., x_T
Each step costs a constant number of arithmetic operations, so a trajectory of generations costs .
What it counts
- The trajectory , the population in each generation.
- The long-run behaviour of the population: extinction, a fixed level, a cycle of period , or an orbit with no period.
- The multiplier of a cycle , the product . The cycle is stable when the absolute value of the multiplier is less than 1. When the multiplier is 0 the cycle is called superstable.
- The Lyapunov exponent , the mean rate per generation at which two nearby starts separate. A negative value means a stable cycle, and a positive value means chaos.
Relation to other models
- Logistic growth model. The continuous model always moves monotonically to . Its Euler method step with step size is a logistic map with parameter , as that page shows. So a large time step, or a long gap between generations, turns smooth growth into cycles and chaos.
- Ricker model. The Ricker model has the same kind of density dependence and the same route to chaos, but its population stays positive for every .
- Leslie matrix. The Leslie model adds age structure but is linear, so it can only grow or decline geometrically. Density dependence such as the factor is what gives the logistic map its cycles.
- Fixed-point iteration. The trajectory is a fixed-point iteration of . Near the fixed point the error is multiplied by about in each step, so the convergence is linear for , , and quadratic at .
- Cycle detection. A floating-point number has finitely many values, so every computed orbit is eventually periodic. Floyd's algorithm or Brent's algorithm finds the exact period of the computed orbit. To find the period of the true attractor, compare values with a tolerance after a transient, as the code of this page does.
Known results in the model
Bounded populations and extinction (theorem). For , maps into itself. For , from every start in .
Proof. The first claim follows from . For and , . So the sequence decreases and is bounded below by 0. Its limit is a fixed point in , and the only one is 0, because .
The equilibrium (theorem). For the map has a second fixed point in . Its multiplier is , so it is stable for . The fixed point 0 has multiplier and is unstable for . For the multiplier is positive and the population approaches from one side. For it is negative and the population overshoots and oscillates with decreasing size. For example, gives , and the trajectory from is . It is a known result that for every start in converges to .
Proof of the multiplier. .
The 2-cycle (theorem). For the map has a cycle of period 2,
with multiplier . The cycle is stable for and superstable at .
Proof. The points of period 2 solve . This is a polynomial of degree 4 that has the fixed points 0 and as roots. Division by these two factors leaves , whose roots are . They are real and distinct exactly when . With and , the multiplier is . It is when , at , and when , at .
At the cycle is with multiplier , and the trajectory from is . The population alternates between a high and a low year.
The period-doubling cascade (known result). At the fixed point gives way to the 2-cycle, and at the 2-cycle gives way to a 4-cycle. The doublings continue at , , , and the values accumulate at . The ratios converge to . Feigenbaum (1978) showed that the same constant holds for a wide class of smooth maps of an interval with one quadratic maximum, so it is universal. At the stable 4-cycle is . A bisection on the period of the attractor agrees with , and to four decimals (measurement).
Chaos and periodic windows (known result). Between and 4, parameters with chaotic orbits are mixed with windows of stable cycles. The widest window has period 3 and opens at . At the stable 3-cycle is . Li and Yorke (1975) proved that a continuous map of an interval with a point of period 3 has points of every period and an uncountable set of orbits that do not approach any cycle (theorem). With , 1000 steps of transient and 200000 steps of average, the Lyapunov exponent is at , at and at (measurement). At it is , the logarithm of the multiplier divided by the period.
The case r = 4 (theorem). If , then .
Proof. . Apply this with .
So at the map is the doubling of an angle in disguise, and for almost every start the Lyapunov exponent is (known result). The computed value with is (measurement).
Loss of digits in floating point (measurement). At an error is about doubled in each step. From , the orbit in double precision differs from an orbit computed with 300 digits by more than 0.1 first at step 52, which matches the 53 bits of a double. A computed chaotic orbit is a faithful trajectory only for a few dozen steps, but its long-run statistics are still useful (heuristic).
Parameters above 4 (theorem). For the points near with go to a negative value and then to . It is a known result that the set of starts that stay in forever is a Cantor set of measure zero. In the population model this means extinction for almost every start.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/logistic-map/. The authors are listed in prov/DM7V7K.jsonl.
"""The logistic map x_(t+1) = r x_t (1 - x_t) as a population model.
orbit gives the trajectory. The other functions give the fixed points,
the 2-cycle in closed form, the multiplier of a cycle, the period of the
attractor found by iteration, and an estimate of the Lyapunov exponent.
Cost: Theta(T) arithmetic operations for T steps.
"""
from __future__ import annotations
import math
from typing import List, Optional, Sequence, Tuple
def step(r: float, x: float) -> float:
"""One generation of the map."""
return r * x * (1 - x)
def orbit(r: float, x0: float, steps: int) -> List[float]:
"""The values x_1, ..., x_steps from the start x0."""
if steps < 0:
raise ValueError("steps must be >= 0")
x = x0 # @line L1
out: List[float] = []
for _ in range(steps): # @line L2
x = r * x * (1 - x) # @line L3
out.append(x) # @line L4
return out # @line L5
def fixed_points(r: float) -> Tuple[float, float]:
"""The two fixed points 0 and 1 - 1/r (r > 0)."""
if r <= 0:
raise ValueError("r must be > 0")
return 0.0, 1 - 1 / r
def two_cycle(r: float) -> Optional[Tuple[float, float]]:
"""The 2-cycle (r + 1 -/+ sqrt((r - 3)(r + 1))) / (2 r), or None for r <= 3."""
if r <= 3:
return None
d = math.sqrt((r - 3) * (r + 1))
return (r + 1 - d) / (2 * r), (r + 1 + d) / (2 * r)
def multiplier(r: float, cycle: Sequence[float]) -> float:
"""The product of f'(x) = r (1 - 2 x) over the points of a cycle."""
m = 1.0
for x in cycle:
m *= r * (1 - 2 * x)
return m
def attractor(r: float, x0: float = 0.3, burn: int = 100000,
max_period: int = 64, tol: float = 1e-9) -> Optional[List[float]]:
"""The cycle that the orbit settles on, sorted, or None if no period <= max_period."""
x = x0
for _ in range(burn):
x = step(r, x)
path = [x]
for _ in range(max_period):
x = step(r, x)
path.append(x)
for p in range(1, max_period + 1):
if abs(path[p] - path[0]) < tol:
return sorted(path[:p])
return None
def lyapunov(r: float, x0: float = 0.3, steps: int = 100000, burn: int = 1000) -> float:
"""The mean of log |r (1 - 2 x_t)| along the orbit."""
x = x0
for _ in range(burn):
x = step(r, x)
total = 0.0
for _ in range(steps):
total += math.log(abs(r * (1 - 2 * x)))
x = step(r, x)
return total / steps
test_logistic_map.py 92 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/logistic-map/. The authors are listed in prov/DM7V7K.jsonl.
"""Tests of the logistic map against the page values and the closed forms."""
import math
import random
from decimal import Decimal, getcontext
from fractions import Fraction
import pytest
from logistic_map import attractor, fixed_points, lyapunov, multiplier, orbit, two_cycle
def close(xs, ys, tol=1e-6):
return len(xs) == len(ys) and all(abs(a - b) < tol for a, b in zip(xs, ys))
def test_page_traces():
assert close(orbit(2.8, 0.2, 6), [0.448, 0.692429, 0.596319, 0.674023, 0.615205, 0.662838])
assert close(orbit(3.2, 0.2, 6), [0.512, 0.799539, 0.512884, 0.799469, 0.513019, 0.799458])
assert orbit(3.0, 0.5, 0) == []
with pytest.raises(ValueError):
orbit(3.0, 0.5, -1)
def test_exact_step_with_fractions():
x = orbit(Fraction(14, 5), Fraction(1, 5), 2)
assert x == [Fraction(56, 125), Fraction(14, 5) * Fraction(56, 125) * Fraction(69, 125)]
def test_fixed_points_and_stability():
for r in (1.5, 2.0, 2.8):
_, xs = fixed_points(r)
assert abs(multiplier(r, [xs]) - (2 - r)) < 1e-12
assert close(attractor(r), [xs], tol=1e-8)
assert abs(fixed_points(2.8)[1] - 0.642857) < 1e-6
assert attractor(0.8) is not None and abs(attractor(0.8)[0]) < 1e-9
assert multiplier(2.5, [0.0]) == 2.5
def test_two_cycle():
assert two_cycle(3.0) is None
for r in (3.1, 3.2, 3.3, 3.4):
p, q = two_cycle(r)
assert abs(r * p * (1 - p) - q) < 1e-12 and abs(r * q * (1 - q) - p) < 1e-12
assert abs(multiplier(r, [p, q]) - (-r * r + 2 * r + 4)) < 1e-12
assert close(attractor(r), [p, q], tol=1e-7)
assert close(two_cycle(3.2), [0.513045, 0.799455])
assert abs(multiplier(3.2, two_cycle(3.2)) - 0.16) < 1e-12
assert abs(multiplier(1 + math.sqrt(6), two_cycle(1 + math.sqrt(6))) + 1) < 1e-9
assert abs(multiplier(1 + math.sqrt(5), two_cycle(1 + math.sqrt(5)))) < 1e-9
def test_period_four_and_three():
assert close(attractor(3.5), sorted([0.826941, 0.500884, 0.874997, 0.382820]))
assert close(attractor(3.83), [0.156149, 0.504666, 0.957417])
assert attractor(3.7) is None
def test_r_four_closed_form_and_lyapunov():
rng = random.Random(7)
for _ in range(20):
theta = rng.uniform(0, math.pi)
xs = orbit(4.0, math.sin(theta) ** 2, 10)
exact = [math.sin(2 ** t * theta) ** 2 for t in range(1, 11)]
assert close(xs, exact, tol=1e-6)
assert abs(lyapunov(4.0) - math.log(2)) < 0.01
assert lyapunov(3.7) > 0.3
assert abs(lyapunov(3.2) - math.log(0.16) / 2) < 1e-3
def test_float_orbit_loses_all_digits_by_step_52():
getcontext().prec = 300
x, ref = 0.2, Decimal(1) / Decimal(5)
first = None
for t in range(1, 100):
x = 4 * x * (1 - x)
ref = 4 * ref * (1 - ref)
if abs(Decimal(x) - ref) > Decimal("0.1"):
first = t
break
assert first == 52
def test_interval_is_invariant():
rng = random.Random(8)
for _ in range(2000):
r = rng.uniform(0, 4)
x = rng.random()
assert 0 <= orbit(r, x, 1)[0] <= 1
assert orbit(4.2, 0.5, 1)[0] > 1
References
- Robert M. May, Simple mathematical models with very complicated dynamics, Nature 261(5560), 1976, pages 459 to 467 (the logistic difference equation as a population model, its fixed points, cycles and chaotic regime)
- Tien-Yien Li and James A. Yorke, Period three implies chaos, The American Mathematical Monthly 82(10), 1975, pages 985 to 992 (a map of an interval with a point of period 3 has points of every period)
- Mitchell J. Feigenbaum, Quantitative universality for a class of nonlinear transformations, Journal of Statistical Physics 19(1), 1978, pages 25 to 52 (the universal ratio 4.669201609 of the period-doubling intervals)
- Steven H. Strogatz, Nonlinear Dynamics and Chaos, 2nd ed., Westview Press, 2015, Chapter 10 (one-dimensional maps, the logistic map, period doubling and Lyapunov exponents)
- J. D. Murray, Mathematical Biology I, An Introduction, 3rd ed., Springer, 2002, Chapter 2 (discrete population models for a single species)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag DM7V7K Edit this page History Report an error Markdown