Algorithm Search⌘K

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 xt+1=rxt(1−xt)x_{t+1} = r x_t (1 - x_t) for a species with separate, non-overlapping generations. The value xtx_t is the population in generation tt as a fraction of a maximum, and rr is the growth factor per generation at low density. The factor 1−xt1 - x_t 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 rr 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 xt∈[0,1]x_t \in [0, 1], the population in generation tt divided by a scale MM. The population is Nt=MxtN_t = M x_t. The scale MM is the population at which the next generation is zero, not the equilibrium level.

The parameter. r>0r > 0, with no unit: the number of offspring per individual per generation that survive to breed when the population is small. In the population model 0<r≤40 < r \le 4.

The update rule. xt+1=f(xt)x_{t+1} = f(x_t) with f(x)=rx(1−x)f(x) = r x (1 - x). In the units of the population, Nt+1=rNt(1−Nt/M)N_{t+1} = r N_t (1 - N_t / M). The slope of the map is f′(x)=r(1−2x)f'(x) = r (1 - 2x).

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 0≤r≤40 \le r \le 4 the map sends [0,1][0, 1] into itself, because x(1−x)x(1 - x) has its maximum 1/41/4 at x=1/2x = 1/2. For r>4r > 4 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.

  1. LOGISTIC-MAP(r, x_0, T)
  2. 1x ← x_0
  3. 2for t ← 1 to T do
  4. 3x ← r x (1 - x)
  5. 4record x_t ← x
  6. 5return x_1, ..., x_T

Each step costs a constant number of arithmetic operations, so a trajectory of TT generations costs Θ(T)\Theta(T).

What it counts

  • The trajectory x1,…,xTx_1, \ldots, x_T, the population in each generation.
  • The long-run behaviour of the population: extinction, a fixed level, a cycle of period pp, or an orbit with no period.
  • The multiplier of a cycle x1,…,xpx_1, \ldots, x_p, the product f′(x1)⋯f′(xp)f'(x_1) \cdots f'(x_p). 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 λ=lim⁡T→∞1T∑t=0T−1ln⁡∣f′(xt)∣\lambda = \lim_{T \to \infty} \frac{1}{T} \sum_{t=0}^{T-1} \ln |f'(x_t)|, 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 dN/dt=rN(1−N/K)dN/dt = rN(1 - N/K) always moves monotonically to KK. Its Euler method step with step size hh is a logistic map with parameter 1+hr1 + hr, 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 xt+1=xter(1−xt)x_{t+1} = x_t e^{r(1 - x_t)} has the same kind of density dependence and the same route to chaos, but its population stays positive for every rr.
  • 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 1−xt1 - x_t is what gives the logistic map its cycles.
  • Fixed-point iteration. The trajectory is a fixed-point iteration of ff. Near the fixed point x∗x^\ast the error is multiplied by about f′(x∗)f'(x^\ast) in each step, so the convergence is linear for 1<r<31 < r < 3, r≠2r \ne 2, and quadratic at r=2r = 2.
  • 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 0≤r≤40 \le r \le 4, ff maps [0,1][0, 1] into itself. For 0<r≤10 < r \le 1, xt→0x_t \to 0 from every start in [0,1][0, 1].

Proof. The first claim follows from 0≤x(1−x)≤1/40 \le x(1 - x) \le 1/4. For r≤1r \le 1 and xt>0x_t > 0, xt+1≤xt(1−xt)<xtx_{t+1} \le x_t (1 - x_t) < x_t. So the sequence decreases and is bounded below by 0. Its limit is a fixed point in [0,1)[0, 1), and the only one is 0, because 1−1/r≤01 - 1/r \le 0. □\square

The equilibrium (theorem). For r>1r > 1 the map has a second fixed point x∗=1−1/rx^\ast = 1 - 1/r in (0,1)(0, 1). Its multiplier is f′(x∗)=2−rf'(x^\ast) = 2 - r, so it is stable for 1<r<31 < r < 3. The fixed point 0 has multiplier rr and is unstable for r>1r > 1. For 1<r<21 < r < 2 the multiplier is positive and the population approaches x∗x^\ast from one side. For 2<r<32 < r < 3 it is negative and the population overshoots and oscillates with decreasing size. For example, r=2.8r = 2.8 gives x∗=0.642857x^\ast = 0.642857, and the trajectory from x0=0.2x_0 = 0.2 is 0.448,0.692429,0.596319,0.674023,0.615205,0.6628380.448, 0.692429, 0.596319, 0.674023, 0.615205, 0.662838. It is a known result that for 1<r≤31 < r \le 3 every start in (0,1)(0, 1) converges to x∗x^\ast.

Proof of the multiplier. f′(1−1/r)=r(1−2+2/r)=2−rf'(1 - 1/r) = r(1 - 2 + 2/r) = 2 - r. □\square

The 2-cycle (theorem). For r>3r > 3 the map has a cycle of period 2,

x±=r+1±(r−3)(r+1)2r,x_\pm = \frac{r + 1 \pm \sqrt{(r - 3)(r + 1)}}{2r},

with multiplier −r2+2r+4-r^2 + 2r + 4. The cycle is stable for 3<r<1+6=3.4494903 < r < 1 + \sqrt{6} = 3.449490 and superstable at r=1+5=3.236068r = 1 + \sqrt{5} = 3.236068.

Proof. The points of period 2 solve f(f(x))=xf(f(x)) = x. This is a polynomial of degree 4 that has the fixed points 0 and 1−1/r1 - 1/r as roots. Division by these two factors leaves r2x2−r(r+1)x+(r+1)=0r^2 x^2 - r(r + 1) x + (r + 1) = 0, whose roots are x±x_\pm. They are real and distinct exactly when r>3r > 3. With x++x−=(r+1)/rx_+ + x_- = (r + 1)/r and x+x−=(r+1)/r2x_+ x_- = (r + 1)/r^2, the multiplier is r2(1−2x+)(1−2x−)=r2−2r(r+1)+4(r+1)=−r2+2r+4r^2 (1 - 2x_+)(1 - 2x_-) = r^2 - 2r(r + 1) + 4(r + 1) = -r^2 + 2r + 4. It is −1-1 when r2−2r−5=0r^2 - 2r - 5 = 0, at r=1+6r = 1 + \sqrt{6}, and 00 when r2−2r−4=0r^2 - 2r - 4 = 0, at r=1+5r = 1 + \sqrt{5}. □\square

At r=3.2r = 3.2 the cycle is 0.513045,0.7994550.513045, 0.799455 with multiplier 0.160.16, and the trajectory from x0=0.2x_0 = 0.2 is 0.512,0.799539,0.512884,0.799469,0.513019,0.7994580.512, 0.799539, 0.512884, 0.799469, 0.513019, 0.799458. The population alternates between a high and a low year.

The period-doubling cascade (known result). At r1=3r_1 = 3 the fixed point gives way to the 2-cycle, and at r2=1+6r_2 = 1 + \sqrt{6} the 2-cycle gives way to a 4-cycle. The doublings continue at r3=3.544090r_3 = 3.544090, r4=3.564407r_4 = 3.564407, r5=3.568759r_5 = 3.568759, and the values rkr_k accumulate at r∞=3.569946r_\infty = 3.569946. The ratios (rk−rk−1)/(rk+1−rk)(r_k - r_{k-1})/(r_{k+1} - r_k) converge to δ=4.669201609\delta = 4.669201609. 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 r=3.5r = 3.5 the stable 4-cycle is 0.826941,0.500884,0.874997,0.3828200.826941, 0.500884, 0.874997, 0.382820. A bisection on the period of the attractor agrees with r3r_3, r4r_4 and r5r_5 to four decimals (measurement).

Chaos and periodic windows (known result). Between r∞r_\infty and 4, parameters with chaotic orbits are mixed with windows of stable cycles. The widest window has period 3 and opens at r=1+8=3.828427r = 1 + \sqrt{8} = 3.828427. At r=3.83r = 3.83 the stable 3-cycle is 0.156149,0.504666,0.9574170.156149, 0.504666, 0.957417. 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 x0=0.3x_0 = 0.3, 1000 steps of transient and 200000 steps of average, the Lyapunov exponent is −0.8725-0.8725 at r=3.5r = 3.5, 0.35480.3548 at r=3.7r = 3.7 and −0.3697-0.3697 at r=3.83r = 3.83 (measurement). At r=3.2r = 3.2 it is ln⁡(0.16)/2=−0.9163\ln(0.16)/2 = -0.9163, the logarithm of the multiplier divided by the period.

The case r = 4 (theorem). If x0=sin⁡2θx_0 = \sin^2 \theta, then xt=sin⁡2(2tθ)x_t = \sin^2(2^t \theta).

Proof. 4sin⁡2a (1−sin⁡2a)=4sin⁡2acos⁡2a=sin⁡22a4 \sin^2 a \,(1 - \sin^2 a) = 4 \sin^2 a \cos^2 a = \sin^2 2a. Apply this with a=2tθa = 2^t \theta. □\square

So at r=4r = 4 the map is the doubling of an angle in disguise, and for almost every start the Lyapunov exponent is ln⁡2=0.693147\ln 2 = 0.693147 (known result). The computed value with x0=0.3x_0 = 0.3 is 0.69310.6931 (measurement).

Loss of digits in floating point (measurement). At r=4r = 4 an error is about doubled in each step. From x0=0.2x_0 = 0.2, 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 r>4r > 4 the points near 1/21/2 with f(x)>1f(x) > 1 go to a negative value and then to −∞-\infty. It is a known result that the set of starts that stay in [0,1][0, 1] 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.

logistic_map.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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)
  4. 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)
  5. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/DM7V7K/text.yaml