Interactive mathematics

Unfolded

Ideas from mathematics that are easier to see than to explain. Spin them, drag them, and change the numbers.

Four dimensions

The tesseract

A square is a line dragged sideways. A cube is a square dragged upward. Drag a cube in a fourth direction, at right angles to all three you know, and you get a tesseract: 16 corners, 32 edges and 8 cubes for faces.

We can't see four dimensions, but we can see a shadow of one. A cube's shadow can be a small square inside a big one. A tesseract's shadow is a small cube inside a big one. Rotate it through the fourth dimension and the inner cube swells until it becomes the outer one. It looks like it's turning inside out, but every cell stays a perfect cube. Only the shadow bends.

Drag to orbitBlue edges are far away in the 4th dimension, amber ones are close
Shape
Spin through the 4th dimension

Rotate 90°, repeat

The dragon curve

Fold a strip of paper in half, then in half again, and again. Unfold it so every crease makes a right angle and look at it edge-on. You've made a dragon.

You don't need the paper. Start with one line. Copy the whole shape, swing the copy 90° around its last point, and attach it. Then do the same to the new shape. After a dozen rounds a coiled, clawed figure appears, and the line never once crosses itself.

Four dragons rotated around their shared starting point interlock perfectly, without a single overlap.

Each color is one round of copy-and-rotateIt stops at round 15. Step back and forth, or drag the round slider.
Color by

Two rules, ten thousand steps

Langton's ant

An ant walks on a grid of blank squares. On a blank square it turns 90° right, paints the square, and steps forward. On a painted square it turns 90° left, wipes it clean, and steps forward. That's the whole program.

For about 10,000 steps the result looks like noise. Then the ant starts building a "highway": a 104-step pattern that repeats and marches off diagonally forever. Every starting grid anyone has tried ends up the same way, but nobody has proved it has to.

Give the ant more colors, one turn for each, and it builds other things entirely.

The grid wraps around at the edgesThe white square is the ant
Rule, one letter per color

z → z² + c

The Mandelbrot set

Pick a point c on the plane. Start at zero, square it, add c, and repeat. Either the numbers stay small forever or they run off to infinity. The points that stay small are the Mandelbrot set, painted black here. The colors show how quickly every other point escapes.

The edge never gets simpler. Zoom in anywhere along it and you find spirals, seahorses, lightning and tiny copies of the whole set, each one slightly different.

Drag to move · scroll or pinch to zoom · double-click to dive in
Go to

137.507764…°

The golden angle

Plant a seed, turn by a fixed angle, plant the next one a little farther out, and repeat. Most angles waste space: the seeds fall into straight spokes with gaps between them. One angle, about 137.5°, never lines up at all, so the seeds pack evenly. Sunflowers, daisies and pinecones grow this way.

Nudge the angle by a tenth of a degree and the spokes come back. Count the spiral arms in the golden pattern and you get Fibonacci numbers: 13, 21, 34, 55.

Try "21 arms" and "34 arms" with the golden angle
Try
Color by

k → m·k (mod n)

Times tables on a circle

Put n points around a circle and number them. Draw a line from each point k to the point m × k, wrapping around the circle when you pass n. Times two draws a heart-shaped cardioid. Times three draws a nephroid with two lobes, times four has three.

Let m slide between whole numbers and the curves melt into one another. Some big multipliers bring back the small ones in disguise.

Each chord joins k to m·k
Try

Circles riding on circles

Fourier circles

Any closed shape can be drawn by a chain of spinning circles. Each circle turns at a whole-number speed and rides on the rim of the one before it. Choose the right sizes and starting angles and the pen at the end of the chain traces your shape.

Working out those sizes is called the Fourier transform. It's one of the most useful ideas in science: it's how JPEG shrinks photos and how your phone pulls a voice out of background noise. A few circles give a rough sketch. Add more and the corners sharpen.

Grey outline: the target. Colored trail: what these circles draw.
Shape

Sensitive dependence

The butterfly effect

In 1963 Edward Lorenz boiled the weather down to three equations and let a computer follow them. The point never settles and never repeats itself. It loops around two wings forever.

Start two paths a hundred-thousandth apart. For a while they move as one. Then the gap explodes and they go completely separate ways. That's why forecasts more than a couple of weeks out are guesswork: tiny errors in today's measurements grow until they swamp everything.

Drag to orbitSet ρ below about 24 and the paths settle down
Paths

Patterns in the primes

Prime spirals

Place every whole number n at distance n from the center, turned n radians. Keep only the primes. Spirals appear. Zoom out and there are dozens of them. Zoom out further and they straighten into rays.

The arms come from fractions that are very close to 2π: 44/7 and 710/113. Numbers 44 apart, or 710 apart, point in almost the same direction, so they line up. Primes skip every arm whose numbers share a factor with 44 or 710, which is why some arms are empty. Even the first 6 arms show it: every prime above 3 sits next to a multiple of 6, so primes only use 2 of them.

Each dot is a number at angle n radians, distance n. Amber dots are primes.
Go to
Show

Random rolls, perfect order

The chaos game

Mark the three corners of a triangle and put a dot anywhere. Roll a die to pick a corner, move halfway toward it, and mark the spot. Then do it again from there. Every move is random, yet after a few thousand rolls the dots form the Sierpinski triangle: a triangle full of triangle-shaped holes, all the way down.

Change the shape or the rule and other fractals appear. Swap the corners for four stretch-and-shift rules and the same random process grows a fern.

Each dot takes the color of the corner it jumped towardUse One step to watch single jumps
Game

Where randomness piles up

The bell curve

Drop a ball onto rows of pegs. At every peg it has an even chance of bouncing left or right, so where any one ball lands is pure luck. Drop thousands and the pile always takes the same shape: the bell curve, also called the normal distribution.

It appears because most paths mix lefts and rights about evenly, and only a few go all one way. Heights, test scores and measurement errors pile up the same way for the same reason: each is the sum of many small random nudges.

White line: the bell curve the bars should approach

Luck in the long run

The law of large numbers

Flip a fair coin 10 times and getting 7 heads, 70%, is nothing special. Flip it 100 times and 60% still happens. But keep flipping and the share of heads gets squeezed toward 50%. After a million flips it's almost always within a tenth of a percent.

Here's the strange part. The share closes in on 50%, but heads minus tails does not close in on zero. It tends to drift further away, growing like the square root of the number of flips. The coin never makes up for a run of tails. The run just gets drowned out by everything that comes after it.

Switch the chart to Heads − tails to watch the gap grow while the percentage settles.

Each line is one coin, flipped again and againShaded: where 95% of coins should be. Each gridline is 10× more flips.
Coins
Chart

Should you switch?

The Monty Hall problem

A game show hides a car behind one of three doors and goats behind the other two. You pick a door. The host, who knows where the car is, opens one of the other doors to show a goat and lets you switch to the last closed door. Two doors are left, so it must be 50–50. Right?

Switching wins 2 times out of 3. Your first pick is right only 1 time in 3, and showing you a goat doesn't change that. The other 2 times, the car is behind the one door the host was careful not to open. In every game, exactly one of the two choices wins.

Still not convinced? Try 100 doors. You pick one, the host opens 98 goats and leaves one other door shut. Would you stick with your first guess?

Gold: the car. Blue ring: your first pick. Pink ring: the door you could switch to.White ticks: where each bar should settle
Doors

π from a pile of needles

Buffon's needle

Draw lines on the floor, one needle-length apart, and drop needles at random. Some land across a line and some don't. In the 1700s the Comte de Buffon worked out that the chance of a crossing is exactly 2/π, about 64%. Count the crossings and you can work backwards to π, without a circle in sight. It sneaks in through the angle: a needle can point in any direction around a circle.

It's a very slow way to find π. Ten times more needles buys only about half an extra correct digit. In 1901 Mario Lazzarini claimed 3.1415929 from 3,408 needles, which almost certainly means he stopped at a lucky moment.

Darts work too. Throw them at a square with a circle inside, and the share that lands in the circle is π/4.

Pink: crossed a line, or landed in the circle. Blue: didn't.The newest one is white
Throw

Shared birthdays

The birthday paradox

How many people do you need in a room before two of them probably share a birthday? Many people guess something near 183, half of 365. The real answer is 23.

The trick is that you're not looking for someone who shares your birthday. Any pair will do, and 23 people make 253 pairs. Each pair has only a 1 in 365 chance of matching, but with that many pairs the chance of at least one match passes 50%. With 70 people a match is 99.9% certain.

Each square is a day. Purple: two or more people share it.White curve: the exact chance. Dots: what the rooms here showed.

A game with no players

The Game of Life

Take a grid of cells, each one alive or dead. At every tick, a live cell with two or three live neighbors survives and a dead cell with exactly three comes alive. Every other cell dies or stays empty. John Conway chose these rules in 1970. You only pick where to start.

Some shapes sit still, some blink, and some walk. The glider shuffles diagonally forever. Bill Gosper found a gun that fires a new glider every 30 ticks, which proved that a pattern can grow without limit. People have since built working computers out of gliders, so anything a computer can do, Life can do too.

Draw your own on the grid. The R-pentomino is only 5 cells, yet on an unlimited grid it churns for 1,103 generations before it settles.

Click or drag to draw cellsNewborn cells glow white and cool to blue as they age
Start with

x → r·x·(1 − x)

The road to chaos

Here is a tiny model of a population. Next year's size is r times this year's, held back by crowding: x becomes r·x·(1 − x), where x runs from 0 (empty) to 1 (full). For small r the population settles on one value. Past r = 3 it can't settle, and it flips between a boom year and a bust year.

Turn r up and the cycle of 2 splits into 4, then 8, then 16, each split arriving about 4.669 times sooner than the last. By r ≈ 3.57 the splits pile up and the values never repeat. That's chaos, from a formula you could work out on paper. Mitchell Feigenbaum found the same 4.669 in every process shaped like this single hump, and it has been measured in real fluids and circuits.

Deep in the chaos there are calm windows. Near 3.83 a cycle of 3 appears, then splits into 6, 12, 24: a tiny copy of the whole picture.

Top: every value x keeps returning to, for each r. Drag the dashed line or click to pick r.Bottom: x, one step at a time, at that r
Try
View

Halve it, or triple it and add 1

The Collatz conjecture

Pick any whole number. If it's even, halve it. If it's odd, triple it and add 1. Repeat. Start at 27 and you climb as high as 9,232 before crashing down to 1 after 111 steps. Every number anyone has tried ends at 1. Computers have checked every starting number past 100 quintillion, but nobody can prove that all of them do.

Here every path is drawn backwards from 1. Each even step bends one way and each odd step bends the other. Paths that end the same way share a stem, so thousands of them grow into one plant. The white line is the number you're following.

Change the two bends to grow seaweed, coral or a tight curl.

Brighter where many paths overlapColor: how many steps a number takes to reach 1
Follow

Back if you can, forward if you must

Recamán's sequence

Start at 0. On step 1 jump 1, on step 2 jump 2, and so on. Each time, jump backward if you'd land on a positive number you haven't visited yet. Otherwise jump forward. That gives 0, 1, 3, 6, 2, 7, 13, 20, 12, …

Draw every jump as a half circle and the sequence weaves itself into loops. The rule tries not to repeat itself, but forward jumps can land on old numbers: 42 is reached on step 20 and again on step 24. Nobody knows whether every whole number is reached eventually. Some small ones hold out for a very long time.

Turn on the sound to hear it. Each jump plays a note for the number it lands on.

Odd steps arc above the line, even steps belowReadout: the smallest number still waiting its turn

Infinite edge, finite area

The Koch snowflake

Start with a triangle. Split every edge into thirds and push a smaller triangle out of each middle third. Then do the same to every new edge, forever.

Every round makes the edge 4/3 as long, so after enough rounds it's longer than any distance you can name. Yet the whole snowflake fits inside a circle, and its area closes in on exactly 8/5 of the triangle you started with. It's an infinitely long fence around a field of ordinary size.

Magnify any piece and you find the same bumps again. Coastlines behave like this too: the shorter your ruler, the longer the coast you measure.

Hover or tap to magnify 4×Anti-snowflake: the same bumps pushed inward. Its area closes in on 2/5.
Shape

A line that fills a square

The Hilbert curve

Can a line with no thickness fill a whole square? In 1891 David Hilbert showed how. Split the square into four and visit the quarters in a U shape. Then split every quarter into four and swap each visit for a smaller U, turned so the ends join up. Repeat.

Each order roughly doubles the length of the line, yet it never leaves the square and never crosses itself. Carried on forever, it passes through every single point of the square.

It also keeps neighbors together: stops close along the line land close together in the square. That's why it's used to store map and image data. Watch the white dot move steadily along the strip below while it wanders all over the square.

The strip is the line pulled straight. Color marks the way along it.Hover or tap a cell to find its place on the strip
Curve

a² + b² = c²

The Pythagoras tree

Put a right triangle on top of a square, then build a square on each of the triangle's two shorter sides. Do the same on top of those two squares, and again, and a tree grows.

Pythagoras' theorem says the two smaller squares together have exactly the area of the square they grow from. So every generation of squares adds up to the area of the trunk, whatever the angle. Point at any square to check.

The Dutch maths teacher Albert Bosman first drew this tree in 1942. At 45° it's symmetric. Lean the angle over and it curls like a fern.

Hover or tap a square to compare it with its two squaresColor: generation

Four grains and it topples

The sandpile

Drop grains of sand onto a grid. A square can hold up to 3 grains. Give it a 4th and it topples, passing one grain to each of its four neighbors, which may topple in turn. Grains pushed off the edge are gone.

Pour at the center and a pattern grows that nobody designed: nested triangles, stripes and four-fold symmetry, sharper the more sand you add. The order in which squares topple never matters. The final pile always comes out the same, which is why it's called the abelian sandpile.

Per Bak, Chao Tang and Kurt Wiesenfeld introduced it in 1987 as a model of systems that tune themselves to the edge of collapse. The piles you get after pouring for a long time can even be added like numbers: pour one onto another and topple. One of them acts like zero and leaves every other one unchanged. Choose "The pile that acts like zero" to build it.

Dark: empty. Blue, pink, amber: 1, 2 and 3 grains. White: about to topple.The view zooms out as the pile grows
Sand

Order without repeats

Penrose tiling

Square tiles repeat: slide the floor over by one tile and it lands on itself. Roger Penrose found tiles that cover a floor forever without gaps, yet can never repeat. However far you slide the pattern, it never matches up.

Here there are just two tiles, a fat rhombus and a thin one. Each round cuts every tile into smaller fat and thin pieces by the same rule. Count them and the ratio of fat to thin closes in on the golden ratio, 1.618…, which isn't a fraction. A repeating floor would give a fraction, so this one can't repeat.

Five-fold symmetry like this was thought impossible in crystals until Dan Shechtman found it in a metal alloy in 1982. It won him the 2011 Nobel Prize in Chemistry. In 2023 a hobbyist, David Smith, found a single tile that does the job alone: the hat.

Gold: fat rhombuses. Pink: thin ones. Try coloring by direction.Each round shrinks the tiles by the golden ratio
Color by

Who's nearest?

Voronoi diagrams

Scatter some points, then color every spot on the plane by whichever point is closest. The plane breaks into cells with straight edges, one cell per point. Every edge lies exactly halfway between two points, and every corner is equally far from three.

The pattern turns up in giraffe skin, dried mud, dragonfly wings and the areas served by cell towers. In 1854 John Snow drew a boundary like this around a London water pump to show that cholera deaths clustered near it.

Join each pair of points whose cells touch and you get the Delaunay triangulation, which avoids thin sliver triangles as well as any triangulation can. Map makers and 3D software use it to turn scattered points into a mesh.

Drag a point to move it. Click empty space to add one.White lines: the Delaunay triangulation

Slide down the tangent

Newton's fractal

Newton's method solves equations by guessing. Start with a guess, follow the curve's tangent line down to zero, and use that point as the next guess. Close to an answer it homes in fast, roughly doubling the number of correct digits with every step.

But which answer does it find? Color every starting point in the plane of complex numbers by the root it ends up at. Each root sits in a calm patch of its own color. Between them the borders break into chains of beads, and wherever two colors meet, all the others are there too.

Drag the roots and the borders rearrange. A step size other than 1 overshoots or undershoots each time and gives the borders a different texture.

Drag the ringed dots, the roots. Hover or tap to follow one guess.Darker: more steps needed
Roots

Gears and a pen

The spirograph

A toothed gear rolls around the inside of a toothed ring, with a pen through a hole in the gear. How many laps until the pattern closes? Count the teeth. With a 96-tooth ring and a 30-tooth gear, the largest number that divides both is 6, so the pen returns to its start after 30 ÷ 6 = 5 laps, having drawn 96 ÷ 6 = 16 points.

A gear that shares no factor with 96, like one with 35 teeth, has to make 35 laps and draws 96 points. It's the greatest common divisor at work, the same arithmetic you use to simplify fractions.

Move the pen toward the gear's edge for sharp loops, or toward its center for gentle waves. Roll the gear around the outside of the ring for a different family of curves.

White dot: the penColor shows how far through the drawing it is
Roll the gear

Pendulums with a pen

The harmonograph

Victorian parlors had a drawing machine run by pendulums: one swings the pen left and right, another swings it up and down. When the two swing in a simple ratio like 2 to 3, the pen traces a Lissajous figure, a closed knot that repeats exactly.

Real pendulums lose energy, so the knot slowly shrinks toward the center. Detune one pendulum slightly and the knot also turns as it shrinks, laying down a spiral of overlapping loops. A third pendulum that swings the paper in circles adds the familiar swirl.

Set the detune and the damping to none and switch off the paper to see the pure Lissajous figure.

Color runs from the first swing to the lastWhite dot: the pen right now
Left–right to up–down

Fifteen pendulums, one minute

The pendulum wave

Hang 15 pendulums in a row, each a little shorter than the last. Tune them so that in one minute the first swings exactly 51 times, the next 52, the next 53, and so on up to 65. Then let them all go at once.

They drift apart into traveling waves, snakes and braids. Halfway through the minute each pendulum is half a swing ahead of the one before it, so they split into two alternating rows. At a third of the minute the pattern repeats every 3 pendulums, and at a quarter every 4. At the full minute every pendulum has made a whole number of swings, and they line up again.

None of it is random: the pattern at any moment depends only on the fraction of the minute that has passed. Drag the time slider to jump to those fractions.

Seen from above: each bob swings up and down the screenEach pendulum swings once more per minute than the one to its left
Pendulums

e^(iπ) = −1

Euler's formula

Put $1 in a bank that pays 100% interest a year. Paid once, you end the year with $2. Paid monthly, about $2.61. Paid every instant, about $2.718: the number e. That's what e to a power means: e^x is what (1 + x/n)^n closes in on as n grows.

Now make x imaginary: iπ. Multiplying by 1 + iπ/n hardly grows a number at all. Instead it turns it a little, plus a tiny stretch. Do that n times and you've turned about π radians, half a circle. As n grows the stretch fades away and you land exactly on −1. So e^(iπ) + 1 = 0, a single line linking five of the most important numbers in mathematics.

Each colored triangle is one step, and they're all the same shape. Try θ = 2π to go all the way around.

Dashed: the unit circle. White ring: where the limit lands, e^(iθ).White dot: where n steps get you
Try

Polynomials in disguise

Taylor series

A computer can only add, subtract, multiply and divide, so how does it find sin x? One way is a polynomial that copies sin x at a single point: the same height, the same slope, the same bend, and so on for as many terms as you like. Every extra term makes the copy hug the curve over a wider stretch.

For sin x and eˣ, enough terms copy the whole curve. For 1/(1 + x²) they can't: around 0 the copy falls apart past x = 1, even though the curve is perfectly smooth. The trouble hides off the number line, at the imaginary numbers ±i, where the function divides by zero. A series only reaches as far as the nearest trouble.

Drag the white dot to build the series around a different point, and watch the shaded zone move with it.

White: the function. Violet: the polynomial. Drag the white dot.Shaded: where adding terms keeps helping
Function

Why 1 comes first

Benford's law

Take the populations of towns, the lengths of rivers or the numbers in a company's accounts, and look only at the first digit. You'd expect each digit from 1 to 9 to lead about one time in nine. Instead about 30% start with 1, and fewer than 5% start with 9.

The reason is growth. Something that grows by a steady percentage spends a long time between 1 and 2, because doubling takes a while, but it rushes from 9 to 10, an 11% step. On a logarithmic scale, the stretch from 1 to 2 covers 30.1% of the way to 10. Powers of 2, Fibonacci numbers and factorials all follow the law exactly in the long run.

Simon Newcomb noticed it in 1881 because the first pages of his book of logarithm tables were the most worn. Auditors now use it to spot invented figures. Pick random numbers from 1 to 999 to see data that doesn't follow it.

Bars: how often each first digit appears. White ticks: Benford's prediction.Each new number's first digit is in amber
Numbers

Random walks that stick

Growing crystals

Put one sticky particle in the middle. Release another far away and let it wander at random, one step in any direction, over and over, until it bumps into the first and sticks. Then release the next one.

You might expect a round blob. Instead you get branching arms, because the tips stick out and catch wandering particles before they can reach the gaps between branches. The same process shapes copper grown by electroplating, mineral dendrites in rock and the branching scars of electric discharges.

Thomas Witten and Leonard Sander described it in 1981. The cluster is a fractal, somewhere between a line and a filled area: its mass grows like its radius to the power of about 1.71, not 2. Lower the stickiness and particles get more chances to slip into the gaps, so the cluster fills in.

Color: how big the cluster was when each particle arrivedThe view zooms out as it grows
Grow

The quickest way down

The brachistochrone

A bead slides without friction from A down to B. Which shape of track gets it there first? The straight line is the shortest, but the bead starts out slowly. A steeper start builds speed sooner, but too steep wastes distance.

In 1696 Johann Bernoulli challenged the mathematicians of Europe to find the answer. Newton, Leibniz, his brother Jakob and others solved it: the fastest track is a cycloid, the curve traced by a point on the rim of a rolling wheel. Galileo had guessed an arc of a circle, which comes close but loses.

Once B is far enough to the right, something strange happens: the fastest path dips below B and climbs back up to it. Try "Far and shallow".

Pink: cycloid. Violet: Galileo's circle. Amber: steep start. Blue: straight line.Drag the white ring to move B
Put B

Circles all the way down

The Apollonian gasket

Draw three circles that touch each other inside a big one. Each curved triangle between them has room for exactly one circle that touches all three of its sides. Fill every gap, then every new gap, forever.

Measure a circle's curvature as 1 ÷ radius, so smaller circles curve more. René Descartes found a simple rule linking four touching circles, and it leads somewhere surprising: if the first four curvatures are whole numbers, every circle in the gasket has a whole-number curvature too. The outer circle counts as negative because it curves the other way.

Apollonius of Perga studied circles touching circles around 200 BC. The gasket still turns up in research on prime numbers: mathematicians have proved that a gasket like this one contains infinitely many circles whose curvature is prime.

Numbers: each circle's curvatureHover or tap a circle to read it
Start with curvatures

223/71 < π < 22/7

Squeezing π

Draw a hexagon inside a circle and another one outside it. The circle's edge is trapped between the two. If the circle is 1 across, its perimeter is π, so π is more than 3 (the inside hexagon) and less than about 3.46 (the outside one).

Now double the number of sides. Each doubling cuts the gap to about a quarter, and both polygons hug the circle tighter. Around 250 BC Archimedes went to 96 sides, working out square roots by hand, and proved that π lies between 223/71 and 22/7.

More and more sides gave the best values of π for well over a thousand years. Ludolph van Ceulen spent decades on it and reached 35 digits, which were carved on his tombstone.

Blue: the polygon inside. Amber: the polygon outside.The lens zooms in on one edge

Where is the middle of a triangle?

The Euler line

A triangle has more than one center. The centroid is where the three lines from each corner to the middle of the opposite side cross: it's the balance point of a cardboard cutout. The circumcenter is equally far from all three corners. The orthocenter is where the three altitudes meet. The incenter is equally far from all three sides.

Drag the corners and the centers wander about, sometimes right out of the triangle. Yet the centroid, circumcenter and orthocenter always stay on one straight line, with the centroid exactly a third of the way along. Leonhard Euler proved it in 1765. The incenter is only on that line when two sides are equal.

Halfway between the circumcenter and the orthocenter sits the center of the nine-point circle. It passes through the middles of the three sides, the feet of the three altitudes, and the points halfway from each corner to the orthocenter.

Drag a cornerG centroid, O circumcenter, H orthocenter, I incenter
Show how each center is found
Try

Morley's miracle

Morley's trisector theorem

Take any triangle and cut each of its angles into three equal parts. Next to each side, two of the cutting lines meet. Join the three meeting points and you always get an equilateral triangle, whatever shape you started with.

Frank Morley noticed this in 1899. The Greeks had every tool needed to prove it, yet missed it. Perhaps that's because an angle can't be cut in three with a ruler and compass, the tools their geometry was built on.

Halves and quarters don't do this. Cut the angles in half and the lines all meet at a single point, the incenter. Cut them in quarters and the middle triangle is no longer equilateral.

Drag a cornerWith thirds, the amber triangle's angles are always 60°
Cut each angle into

Area by counting

Pick's theorem

Stretch a rubber band around some pegs on a square grid. To find the area inside, count the pegs inside the band (I) and the pegs the band touches (B). The area is I + B ÷ 2 − 1 grid squares. No measuring, just counting.

Georg Pick found this in 1899. It works for any polygon with its corners on pegs, as long as its edges don't cross. The readout checks it against the shoelace formula, which works out the area from the corners' coordinates.

There's no version of it for solids. Some tetrahedra have pegs at their four corners and none anywhere else, yet they can be as big as you like.

Click a peg to add a corner. Drag a corner to move it, tap it to remove it.Green: inside. Amber: on the band.

Slices of a cone

Conic sections

Slice a cone with a flat plane. Cut straight across and the edge of the cut is a circle. Tilt the plane and it stretches into an ellipse. Tilt it until it's parallel to the side of the cone and the curve never closes: that's a parabola. Tilt further and the plane cuts both halves of the double cone, giving the two branches of a hyperbola.

Greek geometers studied these curves for their own sake. About 1,800 years later they turned out to be the paths of planets, comets and thrown balls.

Where are the foci? Drop a ball into the cone so it touches the cone all the way round and also touches the plane. It touches the plane exactly at a focus. These Dandelin spheres, found in 1822, give a short proof that the distances from any point of an ellipse to its two foci always add up to the same total.

Drag to orbitGreen: where the plane cuts the cone. White dots: the foci.
Slice

A mirror shaped like a circle

Circle inversion

Pick a circle. Every point inside it is sent to a point outside, and every point outside comes inside, along the same ray from the center. The rule: the two distances from the center multiply to the radius squared. Points on the circle stay put, and the center swaps places with infinity.

It's a mirror, but a strange one. Straight lines turn into circles through the center. Other circles stay circles. Angles where curves cross come out unchanged, so a square grid turns into a web of circles that still meet at right angles.

Inversion turns hard problems about touching circles into easy ones about straight lines, which is how many old puzzles about chains of circles are solved.

Faint: the shape. Bright: its image in the mirror circle.Drag the white handles
Shape

Constant width

Rollers that aren't round

Measure a circle across in any direction and you get the same width. It isn't the only shape like that. Draw an equilateral triangle, then replace each side with an arc centered on the opposite corner. This Reuleaux triangle is just as wide in every direction. Britain's 20p and 50p coins are seven-sided shapes of the same kind.

Rest a board on rollers of constant width and it rides perfectly level, even though the rollers' centers bob up and down. Square rollers make it rock. Every shape of constant width has a perimeter of exactly π times its width, just like a circle.

Spin a Reuleaux triangle inside a square and it touches all four sides the whole time. Its corners sweep out a square with slightly rounded corners, about 98.8% of the whole. Drills built on this idea cut almost square holes.

Rollers: dots trace the centersDrill: pink is the hole cut so far
Scene
Roller

Only five

The Platonic solids

A Platonic solid is built from one kind of regular polygon, with the same number meeting at every corner. There are exactly five: the tetrahedron, cube, octahedron, dodecahedron and icosahedron.

Why only five? At least three faces must meet at a corner, and their angles must add up to less than 360°, or the corner lies flat. Three, four or five triangles fit (180°, 240°, 300°). So do three squares (270°) and three pentagons (324°). Six triangles, four squares or three hexagons make exactly 360° and tile a flat floor instead. Nothing else is left.

Put a dot in the middle of every face and join neighboring dots: you get the dual solid. The cube and octahedron are duals, so are the dodecahedron and icosahedron, and the tetrahedron is its own dual. Slide the morph to cut the corners off one solid until it becomes the other.

Drag to orbitAmber: the solid's own faces. Blue: its dual's faces, growing at the corners.
View
Solid

Room for more

Hyperbolic tilings

On a flat floor, three hexagons fit around a corner, or four squares, or six triangles. Three regular heptagons (seven sides) won't fit: their corners add up to more than a full turn. In the hyperbolic plane they do, because space there spreads out faster the farther you go, like the frills of a lettuce leaf or a coral.

This is the Poincaré disk, a map of the whole infinite hyperbolic plane squeezed into a circle. Every tile is really the same size and shape. They only look smaller near the rim because the map shrinks distances there, the way a world map stretches Greenland. Straight lines show up as arcs that meet the rim at right angles.

Drag to slide the plane: new tiles stream in from the rim, which is infinitely far away. M. C. Escher drew his Circle Limit prints on this same map.

Drag to slide the plane{p, q}: tiles with p sides, q at each corner
Tiling

Seventeen ways

Wallpaper groups

Repeat a pattern across a wall in every direction and, as it repeats, you can also turn it, flip it, or flip it and slide it along. Each combination of moves is a wallpaper group. Draw something and watch the chosen group copy it across the whole plane.

However clever the pattern, there are exactly 17 groups. Turns can only be by a half, a third, a quarter or a sixth of a full circle. A fifth of a turn can never repeat across a whole wall. Evgraf Fedorov proved the count in 1891.

The names describe the moves: a number gives the smallest turn (p4 has quarter turns), m means a mirror and g a glide, a reflection followed by a slide.

Draw on the canvasLines: mirrors. Dashes: glides. Shapes: centers of turns.
Group

Euler, 1736

The bridges of Königsberg

The city of Königsberg sat on both banks of a river and on two islands, joined by seven bridges. People liked to ask: can you take a walk that crosses every bridge exactly once? Try it. Tap a piece of land to start, then tap or drag across the bridges.

In 1736 Leonhard Euler showed it can't be done, and his argument started graph theory. Only the land and the bridges matter, so shrink each piece of land to a dot. Each time you pass through a dot you use two of its bridges, one in and one out. So every dot except the start and the finish needs an even number of bridges.

In Königsberg all four have an odd number. With no odd dots, you can walk a loop from anywhere. With exactly two, you must start at one and finish at the other. With more, no walk exists. Build an 8th bridge, or try drawing the house without lifting your pen.

Tap a place to start, then tap or drag across bridgesBadges count the bridges at each place: pink means odd
Puzzle

Four is always enough

The four color theorem

Color a map so that countries sharing a border always get different colors. How many colors could you need? This made-up continent never needs more than four, and neither does any other map on paper or on a globe. Countries that meet at a single point don't count as neighbors. Pick a color, then click a country to paint it.

Francis Guthrie noticed this in 1852 while coloring a map of the counties of England. The proof only came in 1976, when Kenneth Appel and Wolfgang Haken had a computer check nearly 2,000 special cases. It was the first major theorem proved that way, and not everyone liked it.

The solver colors one country at a time, starting with the most hemmed-in, and backs up when it gets stuck. Ask it for three colors and it usually fails. One country surrounded by an odd ring of neighbors is enough to need a fourth.

Click a country to paint it, click again to clearDashed white borders: two neighbors with the same color
Paint with
Solver may use

R(3, 3) = 6

The party problem

Invite six people to a party. Any two of them have either met before or not. However they're paired up, there will always be three who all know each other or three who are all strangers. Five guests aren't enough to force it: color a pentagon one way and the star inside it the other.

Make it a game. Take turns coloring the lines between guests, you in red and the computer in blue. Whoever completes a triangle in their own color loses. With six guests there's no draw: once every line is colored, there are always at least two triangles whose three sides share a color.

Why? Pick any guest. Of their five lines, at least three share a color, say red. If any two of those three are joined in red, that's a red triangle. If none are, those three are all joined in blue. Frank Ramsey proved in 1930 that patterns like this are unavoidable in any big enough group.

Tap a line, or drag from one guest to anotherDotted lines would finish your own triangle
Play
Guests

Planar graphs

Untangle

Drag the dots until no two lines cross. Every level can be untangled, because each one was made by drawing straight lines across a page and putting a dot wherever two of them meet. A network that can be drawn with no crossings is called planar.

Two small networks can never be untangled. K₅ is five dots, each joined to all the others. K₃,₃ is the old puzzle of connecting three houses to water, gas and electricity without any pipes crossing. However you drag them, one crossing always stays.

In 1930 Kazimierz Kuratowski proved that these two are the only obstacles. A network is planar exactly when there's no K₅ or K₃,₃ hiding inside it, perhaps with extra dots along its lines.

Drag a dot to move itPink lines cross another line
Puzzle

The cheapest network

Minimum spanning trees

Build roads so you can drive from any city to any other, using as little road as possible. The best network never contains a loop, since you could drop one road from the loop and still reach everywhere. A loop-free network that joins everything is called a spanning tree.

There are a staggering number of them. Ten cities can be joined in 10⁸, or 100 million, different ways, and n cities in nⁿ⁻², as Arthur Cayley showed. Yet the shortest one is easy to find. Kruskal's method takes roads from shortest to longest and skips any that would close a loop. Prim's method grows one tree, always adding the shortest road out of it.

Being greedy rarely pays off, but here it's guaranteed to. Otakar Borůvka solved the problem first, in 1926, to plan an electricity network for Moravia.

Drag a city to move it. Click empty space to add one.Colors: separate pieces that Kruskal's method joins up
Method

One side, one edge

The Möbius strip

Take a strip of paper, give one end a half twist and tape the ends together. The loop you get has only one side. Follow the ant: it walks down the middle, never crosses an edge, and after two laps it has painted both "sides" of the paper. Trace the edge and you'll find there's only one of that, too.

Cutting it is even stranger. Cut down the middle and you don't get two loops: you get one loop, twice as long, with two full twists, and now it has two sides. Cut a third of the way in from the edge instead, and the scissors go around twice before they meet. Out come two loops linked together: a thinner Möbius strip and a long loop.

August Möbius and Johann Listing found the strip independently in 1858. Conveyor belts have been made as Möbius strips so that both faces wear evenly.

Drag to turn the stripAmber: the trail the ant has painted
Scissors

V − E + F

Euler's polyhedron formula

Count the corners (V), edges (E) and faces (F) of a cube: 8, 12 and 6. Work out V − E + F and you get 2. Try the octahedron, a soccer ball with its 12 pentagons and 20 hexagons, or a lumpy random rock. It's always 2. Leonhard Euler noticed this in 1750.

Split every face into smaller ones and the counts shoot up, but V − E + F doesn't move. A new edge either splits a face in two or adds a new corner, so its −1 is always canceled by a +1. The only thing that can change the total is a hole.

A doughnut gives 0 and a two-holed pretzel gives −2. In general it's 2 − 2 × the number of holes, a number called the Euler characteristic. It was one of the first signs that a shape has properties no stretching or squashing can change, which is what topology studies.

Drag to turn the shapeCounting: corners amber, edges blue, faces pink
Shape

Glue the edges

The glued square

In some old video games, a ship that flies off the right side of the screen comes back on the left, and one that leaves through the top comes back at the bottom. That screen is secretly the surface of a doughnut, a torus. Roll the square into a tube to join the top and bottom, then bend the tube round to join its ends.

The arrows show how the edges are glued: matching arrows meet, pointing the same way. Flip one pair and you get a Klein bottle. Now a ship that flies off the right comes back on the left upside down, as its own mirror image. Flip both pairs and you get the projective plane.

Neither of those fits in 3D without passing through itself, but a creature living on the square would never notice. It would just find that after some trips, its left and right had swapped.

Click to steer the ship there, or use the arrow keysPink wing on the ship's left, blue on its right
Glue it into a

You can't comb a hairy ball

The hairy ball theorem

Cover a ball in hair and try to comb it all flat, with no partings and nothing sticking up. You can't. Somewhere there's always a cowlick, a point where the hair has no direction to lie in. Drag across the ball to comb it: the cowlicks slide around, but you can never get rid of them all.

A doughnut is different. Comb its hair around the ring and every hair lies flat. Walk a small loop around a cowlick and count how many times the hair turns: that's its index. On any surface the indexes add up to V − E + F, which is 2 for a ball and 0 for a doughnut, so a ball always keeps at least one.

Henri Poincaré proved this in 1885. It means that at any moment, somewhere on Earth, no wind is blowing across the ground.

Drag across the ball to comb itRings mark cowlicks: pink turn with the loop, blue against it
Shape
Dragging will

Borsuk–Ulam

Opposite points

Right now, somewhere on the equator, two exactly opposite points have the same temperature. That isn't luck. It's always true, for any temperature that changes smoothly as you go around. Drag point A around the ring and watch A's temperature minus B's, where B is the point straight across.

Here's why. Walk A halfway round, to where B was. Now A and B have swapped places, so the difference has flipped sign: it's exactly minus what it was at the start. Getting from a positive number to a negative one without jumping means passing through zero, and there A and B match. The chart shows it: its second half is its first half upside down.

On a globe it gets better. Stanisław Ulam guessed, and Karol Borsuk proved in 1933, that any two quantities, like temperature and air pressure, both match at some pair of opposite points at once.

Drag A or B around the ringGreen: opposite points with the same temperature
Where

z → z² + c, with c held still

Julia sets

The Mandelbrot set asks, for each c, whether z² + c stays small when you start from zero. Now hold c still and ask the same question for every starting point z. The points that stay small make up the Julia set of c, and every c gives a different shape.

Drag the marker on the little map to choose c. While c is inside the gray Mandelbrot set, its Julia set is all one piece. Step outside and it shatters into dust: infinitely many points, no two of them joined. That's what the Mandelbrot set is, a map of which c give one piece.

Gaston Julia and Pierre Fatou worked this out around 1918, long before anyone could draw it. In the Siegel disk, points inside never escape and never settle down. Follow one and it circles forever.

Drag on the map in the corner to choose cHover or tap to follow one starting point
Try

Holes all the way down

The Menger sponge

Take a square, cut it into a 3 × 3 grid and throw away the middle piece. Do the same to each of the 8 squares left, and again, forever. That's the Sierpinski carpet. Now do it to a cube: cut it into 27 smaller cubes, remove the one in the center and the six in the middle of each face, and repeat on the 20 that remain.

Every round keeps 20/27 of what was there, so the volume shrinks toward zero. But every hole opens new walls inside, so the surface area grows without limit. After ten rounds the sponge has 5% of the cube's volume and nearly 1,000 times its surface.

Karl Menger described it in 1926. Look at it straight on and its shadow is exactly the Sierpinski carpet.

Drag to turn itDarker faces are farther back, deep inside the tunnels
View

Rewrite, then draw

Plants from rules

Start with a short string of letters and a rule for rewriting each one, like F → FF. Apply the rules to every letter at once, then again to the result, a few rounds over. The string grows fast: six rounds of this plant's rules make 25,159 letters.

Then hand the string to a turtle with a pen. F means step forward and draw, + and − mean turn, [ means remember where you are, and ] means jump back there. The brackets make branches, every branch follows the same rule, and out comes something that looks grown rather than built.

The biologist Aristid Lindenmayer invented these rewriting systems in 1968 to describe how algae and plants grow. Mutate the rule and a new species appears.

The tape is the string, read one letter at a timeColors run from trunk to tips, by how deep in the brackets each step is
Start from

Remove the middle third

The Cantor set

Take a line from 0 to 1 and remove its middle third. Remove the middle third of both pieces that are left, then of all four, and keep going forever. What remains is the Cantor set. Its total length shrinks to zero, yet it still holds infinitely many points, as many as the whole line.

Above it is the devil's staircase. It's flat over every gap and climbs only on the Cantor set itself. So it rises all the way from 0 to 1 while being flat almost everywhere: all of its climbing happens on a set with no length at all.

Write x in base 3. It survives exactly when it can be written without any 1s. Change each 2 to a 1, read the digits in base 2, and you get the staircase's height. Georg Cantor described the set in 1883.

Hover or tap to read x in base 3Try x = 1/4: it's never removed, though no piece ends there

How long is the coast?

The coastline paradox

Measure a coast by walking a pair of dividers along it: set them to a fixed width, step from point to point along the shore, and count the steps. Then do it again with the dividers half as wide. The shorter ruler reaches into bays and around headlands that the longer one stepped over, so the coast comes out longer.

For a smooth shape the answers would settle down to a true length. For a coast they keep growing, for as long as there's smaller detail to find. On a log-log plot the measurements fall on a straight line, and its slope plus 1 is the coast's fractal dimension: 1 for a smooth curve, more for a rougher one.

Lewis Fry Richardson noticed this when atlases disagreed about the lengths of borders. In 1967 Benoit Mandelbrot asked "How long is the coast of Britain?" and answered with a dimension of about 1.25.

Each amber dot is one step of the dividersEvery island is new, so its dimension varies a little

Continuous, nowhere smooth

The Weierstrass function

Add up waves: a cosine, then one three times as fast and half as tall, then one three times faster again and half as tall again, forever. The total is a curve you could draw without lifting your pen, yet it has no slope anywhere. There's no point where it's smooth enough to have a tangent line.

Zoom in on a smooth curve and it straightens into a line; that's what having a slope means. The top curve uses only the first few waves, so it's smooth, and sure enough it flattens. The bottom one uses all of them. Zoom in ten billion times and it's as jagged as ever, because there's always another, smaller wave.

Karl Weierstrass presented it in 1872, and it shocked mathematicians who believed a continuous curve could only have corners at a few isolated points. Its graph is a fractal, with a dimension between 1 and 2.

Heights are stretched to fit each panelTap a panel to zoom in on a different point

Average, then nudge

Fractal mountains

Start with a square and give its four corners random heights. Set the middle of the square to the average of the corners, then nudge it up or down at random. Do the same for the middle of each edge. Now you have four smaller squares. Repeat, with smaller nudges each time.

After six rounds there are 4,096 squares, and it looks like a mountain range. Real mountains are like this too: a ridge seen from far away has the same jagged outline as a rock up close. The roughness sets how fast the nudges shrink. Shrink them slowly for jagged peaks, quickly for rolling hills.

Fournier, Fussell and Carpenter published this recipe in 1982, the same year fractal mountains appeared in the film Star Trek II.

Drag to turn itEach round halves the squares and adds smaller bumps

0, 01, 010, 01001, …

The Fibonacci word

Start with 0 and 01. Each new word is the last one followed by the one before: 010, then 01001, then 01001010, and so on. Their lengths are the Fibonacci numbers. The endless word they build never repeats itself, and the ratio of its 0s to its 1s closes in on the golden ratio, 1.618…

Now walk it. For each letter, step forward. When the letter is a 0, also make a quarter turn: left if it sits in an even position, right if it's odd. The path never crosses itself or visits a point twice, and it folds into squares within squares.

Every three Fibonacci steps the curve grows by 1 + √2 ≈ 2.414, the silver ratio, and holds smaller copies of itself, while its length grows by the golden ratio each step. Its fractal dimension is 3 log φ ÷ log(1 + √2) ≈ 1.64. Alexis Monnerot-Dumaine described it in 2009.

The tape is the word, read one letter at a timeOther turn angles break the squares into new patterns
Turn by
Color by

AB AB AB…

The Lyapunov fractal

The logistic map is a one-line model of a population: x becomes r·x·(1 − x), over and over. For some values of r the population settles into a steady rhythm, and for others it never repeats. Now let r take turns between two values, a and b, in a fixed pattern such as AB AB AB or AABAB AABAB.

Every point in the picture is one pair (a, b). The map runs for hundreds of steps there, and we measure whether two almost equal starting values drift together or apart. That average rate is the Lyapunov exponent, λ. Gold points have λ < 0: order, where the population falls into a cycle. Dark blue points have λ > 0: chaos.

Mario Markus found these pictures in the late 1980s. The pattern BBBBBBAAAAAA gives the one known as Zircon Zity.

Gold: order. Dark blue: chaos. Brighter gold settles faster.Drag to move · scroll or pinch to zoom · hover or tap to watch x
Pattern

Electrons in a magnetic field

Hofstadter's butterfly

Put an electron on a square grid of atoms and switch on a magnetic field. Quantum mechanics allows the electron only certain energies. Which ones depends on the flux α: how much of the field threads through each little square of the grid.

When α is a fraction p/q, the allowed energies split into exactly q bands. Draw the bands for every fraction from 0 to 1, one row each, and a butterfly appears. Look closer and its wings are made of smaller butterflies, and those of smaller ones still.

Douglas Hofstadter found it in 1976 as a graduate student. Each gap between bands carries a whole number, its Chern number, which shows up in the lab as the quantum Hall effect. In 2013, experiments with graphene finally found its fingerprints.

Across: energy E. Up: flux α, the field through each square.Hover or tap a row to see its bands

A hinge in the middle

The double pendulum

Hang a second pendulum from the end of the first and the gentle tick-tock is gone. The lower arm whips over the top, stalls, spins the other way and flails in a dance that never repeats. Nothing here is random. The motion follows Newton's laws exactly, and the computer solves them in thousandth-of-a-second steps.

The trouble is that tiny differences grow. Each of these pendulums starts a ten-thousandth of a degree away from the one before, closer than you could ever measure. For a few seconds they move as one. Then they split up and go their own ways. Here a gap grows about tenfold every second and a half, so to say where a pendulum will be a minute from now, you'd need its starting angle to about 40 decimal places.

Drag a bob to pick a new start. Start with small swings and the pendulums stay together, calm and predictable.

Trails follow the lower bobsDrag a bob to set the start, then let go
Pendulums

No formula for three

The three-body problem

Two stars circling each other trace perfect ellipses forever, and Newton wrote down the formula. Add a third star and there's no general formula at all. Each body pulls on the other two, the pulls change as they move, and the paths knot into a tangle that only step-by-step computing can follow.

A few special starts behave. Three equal masses can chase each other around a figure eight, a dance Cris Moore found by computer in 1993 and Alain Chenciner and Richard Montgomery proved exists in 2000. Drag one body a little off its path to see how long the dance survives.

Most starts don't behave. In the Pythagorean problem, masses 3, 4 and 5 sit at rest on the corners of a 3-4-5 triangle. They fall together, swerve through a long string of near misses, and around t = 60 the lightest is flung out for good while the other two leave as a pair.

Trails show where each body has just beenDrag a body to move it, then let go
Start

Millions of hops, one shape

Strange attractors

Take a point. Feed its x and y into two short formulas made of sines and cosines, and out comes a new point. Feed that one in, and keep going. The point hops around with no pattern you could predict, yet every hop lands somewhere on the same ghostly shape.

That shape is a strange attractor. Here the point hops up to twenty million times, and the brighter a pixel, the more often it landed there. Four numbers, a, b, c and d, control everything. Nudge one and the shape bends, tears apart or collapses into a few dots.

The two maps are named after Clifford Pickover and Peter de Jong, who helped make pictures like these famous.

Brighter means the point landed there more oftenMove a slider and the picture starts over
Map

One row at a time

Rule 30

Start with a row of cells, each on or off. To make the next row, every cell looks at itself and its two neighbors. Three cells can show 8 patterns, and a rule says which of the 8 make a live cell. That gives 2⁸ = 256 rules, each named by reading its 8 answers as a binary number.

Most rules die out, freeze or repeat. Rule 30 doesn't. From a single cell it grows a tangle so irregular that Stephen Wolfram used its center column as the random number generator in Mathematica. Rule 110 grows little structures that travel and collide, and Matthew Cook proved it can, in principle, compute anything a computer can. Rule 184 is traffic: each car moves right if the space ahead is free. With more than half the road full, jams never clear, and they creep backward.

Tap a square in the key at the bottom to flip that answer and invent your own rule.

Each new row is made from the one above itTap the key's bottom squares to flip them
Famous rules
Start from

Three rules, no leader

Flocking

Every bird here follows three rules, and only looks at the birds close by. Don't crowd your neighbors. Fly the way they're flying. Drift toward the middle of the group around you. Nobody is in charge and no bird knows the shape of the flock, yet it gathers, swirls and splits like starlings at dusk.

Craig Reynolds wrote these rules in 1986 and called his birds boids. Versions of them steered the bat swarms and penguin armies in Batman Returns. Move your pointer into the flock to play the hawk, and watch the birds part around you and close up behind.

Turn a rule down to see what it was doing. Without alignment the birds mill about in a cloud. Without separation they pile into tight clumps.

Color shows which way each bird is headingPoint, or touch and hold, to be the hawk

Boom and bust

Predators and prey

Rabbits multiply when foxes are few. Foxes thrive when rabbits are plenty. So the rabbits boom, then the foxes boom, then the rabbits crash, then the foxes starve, and it all starts over. Alfred Lotka and Vito Volterra each wrote this down as a pair of equations in the 1920s.

Plot rabbits against foxes and each cycle is a closed loop: the two populations come back to exactly where they started, every time. The fox peak always trails the rabbit peak, by about a quarter of a cycle when the swings are small. Volterra was trying to explain why the share of sharks and rays in Adriatic fish markets rose during the First World War, when fishing slowed down.

Faint loops: other starts around the balance pointDrag the white ring to start elsewhere

Reaction and diffusion

Turing patterns

Two chemicals share a dish. One, u, is fed in everywhere. The other, v, eats u to make more of itself and slowly breaks down. Both spread out, but u spreads twice as fast as v. From that, and nothing else, come spots, stripes, branching coral and blobs that split in two like cells.

Here's the trick. A patch of v grows by feeding on u, and it drains the u around it. Because u travels further than v, that drain reaches past the patch, so nothing new can start close by. Growth up close and starvation further out set a natural spacing. Alan Turing worked out this recipe in 1952, and biologists have since found it at work in the stripes of some fish and the ridges on the roof of a mouse's mouth.

This is the Gray–Scott model. The feed rate and the kill rate (how fast v breaks down) decide which pattern you get.

Brighter means more of chemical vDrag on the dish to paint in more v
Pattern

Falling into step

Fireflies in sync

In a few places, like the mangroves of Southeast Asia and the Great Smoky Mountains, thousands of fireflies flash together and the whole forest blinks at once. No firefly is in charge. Each has its own natural rhythm, and each nudges its timing a little toward the flashes it sees.

In 1975 Yoshiki Kuramoto boiled this down to a simple model of rhythms that pull on each other. While the pull is weak, the flashes stay scattered, however long you wait. Past a critical strength, a cluster locks together and grows, sweeping in more of the swarm. The same math describes pacemaker cells in the heart, clapping crowds and the sway of London's Millennium Bridge.

The wheel shows where each firefly is in its cycle, with the flash at the top. The arrow is their average: short when they're scattered, long when they flash as one. Its length, r, runs from 0 to 1.

Under the wheel: r over the last 24 secondsBelow 1× critical they never sync

Change the shape, lose the order

Chaotic billiards

A ball on a frictionless table rolls straight and bounces off the cushion at the angle it came in. On a round table that's all very orderly. Every bounce meets the wall at the same angle, so the path never enters a circle in the middle. On an oval table the paths stay tidy too, hugging a smaller oval or a pair of curves.

Now pull the round table apart and join the halves with straight sides, like a running track. In the 1970s Leonid Bunimovich proved that this stadium is chaotic. Here several balls start on the same spot, aimed a ten-thousandth of a degree apart. After a dozen or so bounces each one is on its own, and in time each path covers the whole table evenly. On the round table the same balls stay together for thousands of bounces.

Faint lines: every path so farPress on the table and drag to aim a new shot
Table
Balls

Stretch, cut, wrap around

Arnold's cat map

Take a square picture made of pixels. Slide each row sideways by its height, and wrap whatever sticks out back around to the other side. Then do the same with the columns, sliding each one down. Every pixel lands on a different pixel and nothing is lost, yet the cat is torn into stripes. A few more rounds and it's static.

Keep going anyway. There are only so many ways to shuffle the pixels, so the scramble has to repeat, and when it does, the cat comes back perfectly. When it comes back depends on the grid's size in odd ways. A 150-pixel square takes 300 steps, while a bigger 199-pixel square needs only 11. On the 89-pixel grid the cat shows up upside down halfway, at step 11.

Vladimir Arnold used a cat's face to explain this map in the 1960s, and the name stuck.

Bars: steps to come back, for every grid size up to 240Show the stretch to watch each step slowly
Grid size (pixels across)

Will it ever come home?

Random walks

A walker stands on a lattice and keeps stepping to a random neighbor: left or right on a line, or north, south, east or west on a grid. Will it ever get back to where it started? In 1921 George Pólya proved that on a line or a flat grid the answer is yes, for certain. Wait long enough and every walker comes home, and then comes home again, forever.

In three dimensions it's different. Only about 34% of walkers ever make it back, and the rest wander off for good. There are just too many ways to get lost. Shizuo Kakutani put it this way: a drunk man will find his way home, but a drunk bird may get lost forever.

The flat grid is the slow one. After 100,000 steps more than a fifth of the walkers still haven't been home, even though every one of them eventually will.

Blue: still out wandering. Gold: has been home. White trail: walker 1.White curve: the exact share. Drag to turn the 3D lattice.
Walk on

Why the house always wins

Gambler's ruin

You sit down with 50 chips and bet 1 chip at a time on a coin flip. You'll stop when you're broke or when you reach 100. On a fair coin your chance of reaching the goal is exactly your start divided by your goal: 50 ÷ 100, so 50–50. Fair, but slow. On average the game lasts start × (goal − start) bets, which is 2,500 of them.

Now tilt the odds a little. Betting on red at American roulette you win 18 times in 38, about 47.4%. That small edge works on you at every single bet. Starting with 50 and aiming for 100, you reach your goal only about 1 time in 200.

Against a house edge, the more bets you make, the surer your ruin. Your best hope is to bet big and bet rarely.

Each line is one gambler's chips, bet by bet. Green: reached the goal. Pink: went broke.Dashed: the average drift. White tick: the exact chance.
Chance of winning each bet

When does water get through?

Percolation

Make a grid of squares and open each one with chance p, like the gaps in a filter or the cracks in a rock. Pour water on top. It can only flow between open squares that share a side. Does it reach the bottom?

When p is small the open squares form little islands and the water soon gets stuck. Push p up and the islands join, all of a sudden. On an endless grid the switch comes at p ≈ 0.593: below it the water always gets stuck somewhere, and above it there's a path that goes down forever. The bigger the grid, the sharper the switch. These grids are twice as wide as they are deep, so the water only has to cross the short way and gets through a little before 0.593.

The same sudden switch shows up when forest fires spread, when epidemics take off and when coffee drips through its grounds, which is where the percolator gets its name.

Gold: wet. Gray: open but dry. Dark: blocked.Chart: how often water gets through at each p, for this grid (gold) and the other sizes (gray)
Grid
Color by

What does random mean?

Bertrand's paradox

Draw a triangle with equal sides inside a circle. Now draw a chord of the circle at random. What's the chance the chord is longer than a side of the triangle? In 1889 Joseph Bertrand gave three different answers, and all three are correct.

Join two random points on the circle and the answer is 1/3. Pick a random radius, then a random point along it, and cut straight across there: 1/2. Pick a random point anywhere inside the circle to be the chord's middle: 1/4. Each is a fair way to choose a chord, but each spreads the chords out differently.

The lesson is that "at random" means nothing until you say how. A chord beats the triangle exactly when its middle lies inside the dashed circle, which has half the radius. Drag the white dot to see.

Purple: longer than the triangle's side. Gray: shorter.Drag the white dot to move a chord's middle
Choose each chord by
Draw

Got, got, need

The sticker album

An album has 50 stickers and each pack holds one, chosen at random. How many packs until the album is full? The first stickers come fast, since almost every pack is new. But when you need just one more, only 1 pack in 50 has it, so the last sticker alone takes 50 packs on average.

Add up all the waits and you get n × (1 + 1/2 + 1/3 + … + 1/n), which is close to n × (ln n + 0.58). For 50 stickers that's about 225 packs: roughly 34 for the first half of the album and 191 for the second. Mathematicians call it the coupon collector's problem.

An album of 680 stickers would take about 4,800 random stickers on your own, which is why collectors swap their doubles.

Top: the album. Middle: packs it took to find each new sticker. Bottom: packs per full album.White: what to expect
Stickers in the album

When to stop looking

The 37% rule

You're hiring, and 100 people will come in one at a time, in random order. After each interview you must say yes or no on the spot, and a no is final. You only want the very best one. What's your plan?

Turn away the first 37, just to learn what good looks like. Then hire the first person who beats everyone you've seen. You'll land the very best about 37% of the time, which is remarkable when a random pick wins only 1 time in 100. The best fraction to skip is 1/e ≈ 0.368, and the chance of success comes out to 1/e too.

It's known as the secretary problem. People apply it, half seriously, to flat hunting and dating.

Bars: candidates in the order they arrive. Gray: turned away to learn. Ring: who you hired.Click the chart to set the cutoff
Candidates

What a positive test really means

Bayes' theorem

An illness affects 1 person in 100. A test catches 90% of the people who have it, but it also flags 9% of healthy people by mistake. You test positive. What's the chance you're sick? Many people, doctors included, guess about 90%.

Count instead. Out of 1,000 people, 10 are sick and 9 of them test positive. Of the 990 healthy people, about 89 test positive too. So 98 people test positive and only 9 of them are sick: about 9%. When an illness is rare, the false alarms from the big healthy crowd swamp the real cases.

Thomas Bayes worked out the rule in the 1700s. It's why a positive result is usually checked with a second test. If the two tests make their mistakes independently, a second positive raises the chance to about 50%.

Pink: sick. Gray: healthy. Ring: tested positive.Move the sliders to change the illness and the test

Tomorrow depends only on today

Markov chains

Here's a toy weather forecast. If today is sunny, tomorrow is sunny with chance 70%, cloudy 20% and rainy 10%. Cloudy and rainy days have odds of their own. Tomorrow depends only on today, not on last week. That one rule makes a Markov chain.

Let it run and count the days. The shares of sunny, cloudy and rainy settle on fixed values, and they're the same whichever day you start on. The forecasts show why: start on a sunny day or a rainy one, and a week later the odds look almost the same. The chain forgets where it began.

Andrey Markov invented these chains in 1906, and in 1913 he used one to study the letters of Pushkin's poem Eugene Onegin. Google's first PageRank treated the whole web as a Markov chain.

Arrows: the chance of tomorrow's weather. The bright dot is today.Click a weather to start there. White ticks: the long-run share.
Change the odds after a day that's

There's always a better pick

Penney's game

You and a friend each pick a run of three coin flips, like heads, heads, tails. Then you flip a coin over and over until one of the two runs turns up. Any run of three is as likely as any other, so it should be a fair game. It isn't.

Whatever you pick, your friend can pick a run that wins more often. The trick: take your middle flip, swap it, and put it in front of your first two. Against HHT they pick THH and win 3 times in 4. Against HHH, THH wins 7 times in 8, because HHH can only win if the first three flips are all heads.

It's like rock, paper, scissors: THH beats HHT, which beats HTT, which beats TTH, which beats THH. There's no best run, only a best reply. Walter Penney published the game in 1969.

Purple: your run. Gold: your friend's. White ticks: the exact chance.Table: the best reply to every pick
Your run
Your friend's run

The rich get richer

Pólya's urn

An urn holds one red ball and one blue ball. Draw a ball at random, then put it back along with another ball of the same color. Repeat. Early luck snowballs: whichever color gets ahead becomes more likely to be drawn again.

Each urn soon settles down. Its share of red stops moving and locks onto a value, but that value is random. One urn ends near 80% red, another near 15%. Run many urns and the final shares spread out evenly from 0% to 100%: every split is equally likely.

George Pólya and Florian Eggenberger studied it in 1923 as a model of contagion, where each case makes the next one of its kind more likely. Start with more balls and the urns settle closer to their starting mix.

Each line is one urn's share of red. Left: the balls in urn 1.Right: where 1,000 urns are now. White curve: where they end up.
Start each urn with

Sifting out the primes

The sieve of Eratosthenes

Write out the numbers from 2 up. The first one, 2, is prime, so cross out every multiple of 2. The next number still standing, 3, must be prime too, because nothing smaller divides it. Cross out its multiples, then do the same for 5, 7, and so on.

Each prime can start crossing at its own square: 7 begins at 49, since 14, 21, 28, 35 and 42 already fell to 2, 3 or 5. That's also why you can stop early. Once the next prime's square is past the end, every number left standing is prime. Eratosthenes, who also measured the size of the Earth, is credited with the idea about 2,200 years ago.

Set the grid to 6 columns. Every prime after 3 is one more or one less than a multiple of 6, so the primes fall into just two columns.

Bright cells are primes. Crossed cells are colored by their smallest prime factor.Hover or tap a number to factor it
Numbers up to

Every even number, two primes

Goldbach's comet

In 1742 Christian Goldbach and Leonhard Euler traded letters about a guess: every even number bigger than 2 is the sum of two primes. 28 is 5 + 23 or 11 + 17. 100 is 3 + 97, 11 + 89, 17 + 83, 29 + 71, 41 + 59 or 47 + 53. Computers have checked every even number up to 4 × 10¹⁸, and nobody has found a proof.

Plot how many ways each even number can be split and you get a comet. The count grows, so the guess only gets safer, but the dots fall into separate bands. Multiples of 3 sit in the top band with about twice as many pairs. Every prime above 3 leaves a remainder of 1 or 2 when divided by 3. A multiple of 3 can pair them as 1 + 2 or 2 + 1, but any other even number needs both remainders the same, and only one of those combinations works.

Up to 10,000, only 4, 6, 8 and 12 have a single way.

Top: ways to split each even n. Pink: multiples of 3 (or 5, 7).Bottom: arcs join primes that add up to n. Tap to pick n.
Try
Color multiples of
Numbers up to

Whole numbers with an imaginary part

Gaussian primes

Allow whole numbers to have an imaginary part, like 3 + 2i, and some ordinary primes stop being prime. 5 = (2 + i)(2 − i), because i × i = −1. Others never split. Each square here is a Gaussian prime: a number a + bi that can't be broken into smaller ones.

Which primes split? Exactly the ones that are a sum of two squares, like 13 = 3² + 2². Apart from 2 = 1² + 1², those are the primes that leave remainder 1 when divided by 4. Primes like 3, 7 and 11, which leave remainder 3, stay prime and sit alone on the axes. Off the axes, a + bi is prime exactly when a² + b² is an ordinary prime.

The pattern looks the same after a quarter turn or a flip across a diagonal, eight ways in all. Multiplying by i turns a number a quarter turn, and that never changes whether it's prime. Carl Friedrich Gauss worked this out around 1830.

Amber: a² + b² is prime. Blue: primes 4k + 3. Pink: 1 + i.Hover or tap any point to factor it
Split a prime

Pull a string tight

The best fractions

π is close to 22/7, and much closer to 355/113, which is right to six decimal places. Zu Chongzhi found it in China about 1,500 years ago. Where do fractions that good come from?

Each dot here is a fraction p/q: q steps across and p steps up, with the whole-number part slid away so only the digits after the point are left. The closer a dot is to the line, the better the fraction. Pull one string tight against the dots from below the line and another from above. The strings turn exactly at the best fractions, the dots closer to the line than any before them. Count the steps along each straight stretch and you get π = 3 + 1/(7 + 1/(15 + 1/(1 + 1/(292 + …)))), its continued fraction. A long stretch like 292 hugs the line for a long way, which is why 355/113 is so good.

The golden ratio φ is all 1s, so its strings turn at every dot and never hug the line. That makes it the hardest number of all to approximate with fractions. Its best ones are ratios of Fibonacci numbers: 3/2, 5/3, 8/5, 13/8, …

Dots are fractions p/q. The strings turn at the best ones.Drag the ring on the line to try your own number
Number

A circle on every fraction

Ford circles

Stand a circle on every fraction p/q between 0 and 1, written in lowest terms, touching the number line, with radius 1/(2q²). Simple fractions get big circles, complicated ones get tiny ones. There are infinitely many, crammed into a line one unit long, and yet no two of them ever overlap. Neighbors just touch.

Which ones touch? Two circles on a/b and c/d kiss exactly when ad − bc is 1 or −1, and otherwise they keep apart. In the gap between two kissing circles, the biggest new circle sits on their mediant: add the tops and add the bottoms, so 1/3 and 1/2 make 2/5. That circle kisses both, leaving two smaller gaps, and so on forever.

Zoom in on any spot and the same picture keeps appearing. Lester Ford described these circles in 1938.

Color: the denominator q. Green: circles touching the chosen one.Tap a circle; the zoom closes in on where you tap

Add the two above

Pascal's triangle

Start with a 1 at the top. Every number below is the sum of the two above it, so row 4 reads 1, 4, 6, 4, 1. Each row adds up to twice the row before, which makes row n add up to 2ⁿ. The numbers count choices too: counting from 0, number k in row n is how many ways there are to pick k things out of n.

Now ignore the numbers and color only the odd ones. A Sierpinski triangle appears, and it gets more detailed the more rows you add. Divide by 3, 5 or 7 instead and color by the remainder, and new fractals grow, made of smaller copies of themselves, 3, 5 or 7 along each side. Dividing by 4 or 6 gives messier patterns, because those aren't prime.

The odd numbers hide one more trick: row n has exactly 2ᵏ of them, where k counts the 1s in n written in binary. Row 6 is 110 in binary, and its odd numbers are 1, 15, 15, 1.

Color: the remainder. Dark: it divides evenly.Hover or tap any number to see it
Remainder after dividing by

Groups of groups of dots

Factorization diagrams

Draw n as n dots, arranged by its prime factors. 6 is 3 × 2, so it's three pairs set on the corners of a triangle. 12 is 2 × 2 × 3: four triangles on the corners of a square. Each factor puts copies of the smaller picture around a polygon with that many corners.

A prime has no smaller factors, so it can only be a single ring of dots. Watch the counting and the primes jump out: after the busy, symmetric 60 comes 61, one plain circle. Numbers with many small factors, like 64 or 360, make the most intricate pictures.

The mathematician Brent Yorgey came up with these pictures in 2012.

Biggest factor on the outside, pairs of 2s drawn as squaresIn the table, pink numbers are primes. Click one to open it.
Show

Ten digits, ten directions

A walk on π

Turn the digits of π into a walk. Each digit from 0 to 9 points one of ten ways around a compass, and you take one step that way for every digit: 1, then 4, then 1, 5, 9, 2, 6, … After 10,000 digits the path has wandered like someone lost in fog. Nobody has proved it, but π's digits seem to behave just like random ones, with each digit turning up a tenth of the time and no pattern at all.

Now walk a fraction. 22/7 = 3.142857142857… repeats, so its walk marches off in a straight line. 355/113 matches π to six decimal places, then repeats every 112 digits, tracing the same squiggle again and again. Every fraction repeats eventually. π, e and √2 never do, because they aren't fractions.

Watch π around step 762: six steps in a row the same way. That's 999999, known as the Feynman point.

Cool to warm: early digits to late ones. Compass: each digit's direction.Gray: a walk on random digits
Number

Proofs without words

Counting with dots

How much is 1 + 2 + 3 + … + 100? Stack the numbers as rows of dots and you get a staircase. Take a second copy, turn it upside down and push it against the first. Together they make a rectangle 100 dots tall and 101 wide, so one staircase holds half of 100 × 101, which is 5,050. The same move works for any n: 1 + 2 + … + n = n(n + 1) ÷ 2. These are the triangle numbers, 1, 3, 6, 10, 15, …

The other pictures work the same way. Bend each odd number into an L and the Ls nest into a square, so 1 + 3 + 5 + 7 = 4². Two triangle numbers in a row also make a square, 10 + 15 = 5². Strangest of all, the cubes: 1 + 8 + 27 + 64 = 100 = (1 + 2 + 3 + 4)². Each cube k³ is k squares of k × k dots, and they fill an L-shaped band exactly k dots wide.

No algebra needed. You can see each answer is right just by counting the sides.

Same dots, moved around: the count never changesThe outline shows the finished shape's sides
Proof

Read it out loud

Look and say

Start with 1 and read it aloud: "one 1". Write down what you said, 11. Read that: "two 1s", so 21. Then "one 2, one 1" gives 1211, then 111221, 312211, and so on forever. No digit bigger than 3 ever shows up.

Each term is about 30% longer than the one before. John Conway proved that the ratio settles on 1.303577…, now called Conway's constant. It's the only positive root of a polynomial of degree 71, an oddly specific number to come out of such a childish game.

Conway also found that from the 8th term on, every term splits into pieces that never affect each other again, each one growing on its own. Exactly 92 kinds of piece turn up, and he named them after the chemical elements, from hydrogen (22) to uranium (3). Switch to Pieces to watch them settle into a steady mix.

Each bracket is a run of one digit, read as a count and the digitPieces: each row is one term, stretched to the same width. Hover for details.
Show

Four numbers, one move

Matrices

A 2×2 matrix is four numbers in a box, but it's best seen as a move. Its first column says where the arrow (1, 0) lands, and its second column says where (0, 1) lands. Every other point comes along for the ride, so the grid stays a grid: lines stay straight, parallel and evenly spaced, and the origin stays put.

The shaded square shows the determinant, ad − bc: the factor by which every area grows or shrinks. When it turns negative, the plane has been flipped over like a page turned face down, and the F reads backwards. At zero, the whole plane is squashed onto a line, and nothing can undo that.

Every turn, zoom and tilt in a video game or a photo editor is a matrix like this one, or a bigger cousin for 3D.

Blue arrow: where (1, 0) lands. Pink: where (0, 1) lands.Drag the arrow tips
Try

Directions that don't turn

Eigenvectors

Feed an arrow v into a matrix and a new arrow, Av, comes out, usually pointing somewhere else. But a few special directions only get stretched, shrunk or flipped around. Those are the eigenvectors, and the stretch factor is the eigenvalue λ (lambda): Av = λv.

Watch the white arrow sweep around the circle while the pink one chases it around an ellipse. Each time they line up, you've found an eigenvector. A shear has just one such direction, and a rotation has none at all, because it turns everything.

Multiply by A over and over and almost any arrow swings toward the direction that stretches most. That trick, power iteration, is how Google's original PageRank ranked the web.

White: v. Pink: Av. Dashed: eigenvectors found so far.Drag the white arrow
Matrix

Times means turn

Complex multiplication

A complex number is a point on a flat plane: an arrow with a length and an angle. Adding two of them just chains the arrows. Multiplying is stranger and much prettier: the lengths multiply and the angles add. So multiplying by w turns the whole plane by w's angle and stretches it by w's length.

That's why i × i = −1. The number i has length 1 and points straight up, at 90°. Two quarter turns make a half turn, and half a turn from 1 lands on −1. The shaded triangles are the same shape, one turned and stretched into the other.

Keep multiplying by the same z and its powers wind out (or in) along a spiral. Land exactly on the unit circle at the right angle and after n steps you're back at 1: the n roots of 1 sit at the corners of a regular polygon.

Blue: z. Pink: w. Amber: their product, or the path of the powers of z.Drag the dots
Show

Painting a function

Domain coloring

A complex function takes a point of the plane and gives back another point, so a true graph would need four dimensions. Here's the way around it: paint every point z by where f(z) lands. The hue shows the direction of f(z), read off the little wheel, and the brightness steps up each time its size doubles.

Zeros, where f(z) = 0, show up as dark points ringed by every color. Poles, where f blows up, are pale ones. Go counterclockwise around a zero and you pass the colors in the wheel's order. Around a pole they run backwards, and around the double zero of z² you pass them twice.

Pick Your own and drag the zeros a and b and the pole p. Push a zero into the pole and the two cancel out. Engineers read maps of zeros and poles like this to tell whether a circuit or a control system will settle down or run wild.

Hue: the angle of f(z). Dark: near a zero. Pale: near a pole.Point to read f(z). Drag a, b and p.
Function

Two ways to say one polynomial

Roots and coefficients

There are two ways to pin down a polynomial like z³ + a₂z² + a₁z + a₀. You can list its coefficients, the a's, or its roots, the points where it equals zero. Roots to coefficients is easy: multiply out (z − r₁)(z − r₂)(z − r₃), and the sum of the roots comes out as −a₂. The other way is hard. From degree 5 up there's no formula like the quadratic formula, so computers hunt the roots down step by step.

Drag a root and the coefficients swing around. Drag a coefficient and the roots slide along. Now loop a₀ once around and bring it back exactly where it started. It's the same polynomial, yet two roots have traded places: the loop went around a spot where they would collide.

Vladimir Arnold used loops like this, and the ways they shuffle roots, to prove that no formula for degree 5 can exist.

Left: the roots. Right: the coefficients. ×: where a₀ makes a double root.Drag either side
Degree

One missing corner

Completing the square

How do you solve x² + 10x = 39? Draw it. Make x² a square with sides x, and 10x a strip 10 wide and x tall. Cut the strip in half and swing one half around to the bottom. Now you almost have a bigger square, x + 5 on a side. Only one corner is missing: a small 5 × 5 square.

Fill in the corner by adding 25 to both sides: (x + 5)² = 64. So x + 5 = 8, and x = 3. Do the same with letters instead of numbers and out falls the quadratic formula. The graph shows the rest: the parabola bottoms out right below −b/2, and it also crosses at −13, an answer a picture made of lengths can't show.

This is how al-Khwarizmi solved this very equation around the year 820. The title of his book gave us the word algebra.

Blue: x². Violet: the strip. Amber: the missing corner.Graph: y = x² + bx − area, and its lowest point
Step

Algebra you can hold

(a + b)³

Why is (a + b)² equal to a² + 2ab + b², and not just a² + b²? Draw a square with sides a + b and cut each side where a ends. You get a square of a², a square of b², and two rectangles of a × b that are easy to forget.

Do the same to a cube and it falls into eight boxes: one a³, one b³, three slabs of a²b and three rods of ab². So (a + b)³ = a³ + 3a²b + 3ab² + b³. The numbers 1, 3, 3, 1 count how many ways you can pick a's and b's, one from each of the three sides.

Before algebra had symbols, this was the proof. Babylonian and Greek mathematicians argued with pictures of cut-up squares, and the cube version is the idea behind the old pencil-and-paper method for cube roots.

Blue: a³. Violet: a²b. Pink: ab². Amber: b³. Grid: unit cubes.Drag to turn the cube
Shape

Mixed up, then not

Perfect shuffles

Cut a deck exactly in half and riffle the halves together so the cards alternate perfectly, with the top card staying on top. That's an out-shuffle, and it looks like a good mix. But do it 8 times to a 52-card deck and every card is back where it started.

The reason is that a perfect shuffle isn't random at all. Each card follows a fixed rule: counting places from 0, the card in place i moves to place 2i, wrapping around after 51 places, while the bottom card stays put. So the cards travel in fixed loops, and the deck comes home once every loop is complete. Change the deck size and the answer jumps around: 50 cards need 21 shuffles, 64 cards only 6.

Magicians practice these for years. Tuck the top card in instead (an in-shuffle) and a 52-card deck takes 52 shuffles to come back, and after 26 of them it's exactly upside down.

Color: where each card started. Paths: one row per shuffle. Loops: the places each card cycles through.Tap a card to follow it
Shuffle
Show

The arithmetic of moves

Symmetry groups

Cut a triangle out of paper and lay it in its outline. How many ways can you pick it up and put it back so it fits? You can turn it by 120° or 240°, flip it over along one of three mirror lines, or leave it alone: six moves in all. A square has eight.

One move followed by another always equals a single move from the same list. That's what makes them a group, and the table records every pair. Look closely and you'll see that order matters: a turn then a flip isn't the same as that flip then the turn. Two flips always make a turn, and every row and column holds each move exactly once.

Groups like this one describe the symmetries of crystals, molecules and the Rubik's cube. They're also the tool Galois used to explain which equations can be solved by a formula.

Numbers: the corners. Dashed: the outline and the mirror lines.Tap a square of the table
Shape
Moves

Times, by adding lengths

The slide rule

Logarithms turn multiplying into adding: log(a × b) = log a + log b. A slide rule is that fact made of wood. Both scales put each number x at a distance log x from the left end, so sliding one scale along the other adds two lengths, and adding the lengths multiplies the numbers.

Set C's 1 over the 2 on D and every number on C sits over its double. Slide the cursor to 3 on C and read 6 below it. The same setting divides, too: 6 on D over 3 on C leaves 2 under the 1. Run past 10 and you use the other end of C, and keep track of the decimal point in your head.

Engineers carried these for over 300 years, from the 1620s until pocket calculators arrived in the 1970s. Apollo 11 took one to the Moon as a backup.

Top strip: C, which slides. Below it: D. Green line: the cursor.Drag the slide or the cursor
Try

Area, one strip at a time

Riemann sums

How do you find the area under a curve? Slice it into thin strips, treat each strip as a rectangle, and add up the rectangles. Some poke above the curve and some fall short, so the answer is a little off. Thinner strips make the error smaller.

Where each rectangle takes its height matters. Use the left or right edge and doubling the strips only halves the error. Use the middle, or slant the tops into trapezoids, and doubling the strips cuts the error by four. On the log chart below the curve, those lines fall twice as steeply.

Bernhard Riemann made the idea exact in 1854: the area is whatever these sums close in on as the strips get thinner. Try 1/x from 1 to e, where the area is exactly 1.

Top: the strips. Bottom: error against n, on log scales.Drag a and b along the axis
Height from
Curve

Rise over run, as the run shrinks

The derivative

How steep is a curve at a single point? A slope needs two points: rise ÷ run. So pick a second point a short distance h further along and draw the line through both. That line is a secant, and its slope is easy to work out.

Now slide the second point closer. As h shrinks toward 0, the secant swings into the tangent, the line that just grazes the curve, and its slope settles on one number. That number is the derivative. Drag the white dot along the curve and its slope is traced out below, drawing a new graph called f′.

Try sin x: its slope traces out cos x. And eˣ traces out itself.

Pink: the secant through two points h apart. Dashed: the tangent.Drag the white dot, or the pink one to change h
Curve

Two halves of calculus, one idea

The fundamental theorem

Sweep a line across a curve and keep a running total of the area behind it. That total is a new function, A(x), drawn below. Where the curve is high, area piles up fast. Where the curve dips below the axis, area counts as negative and the total falls.

Now look at how steep A is: its slope at every point is exactly the height of the curve there. Push the line a tiny step Δx and you add a sliver about f(x) tall and Δx wide, so A rises by about f(x) × Δx. Rise ÷ run leaves f(x). Finding areas and finding slopes undo each other.

Newton and Leibniz each worked this out, in the 1660s and 1670s. Try e^(−x²): its area has no formula at all, yet the slope of A is still the curve.

Top: f and the area up to x. Bottom: that area as a graph, A(x).Drag the line
Curve

Finite inside, infinite outside

Gabriel's horn

Take the curve y = 1/x, from x = 1 outward forever, and spin it around the x-axis. You get a horn that never ends. It keeps narrowing but never closes up.

Slice it into thin discs and add up their volumes: the total is exactly π. The discs shrink so fast that the sum stops growing. Now add up the rings that make its surface. Each ring at x has length 2π/x, and those add up like 1 + 1/2 + 1/3 + …, which grows without limit. So the horn holds π units of paint, yet that paint could never coat its inside wall. (The catch: real paint has a thickness, and far enough out the horn is thinner than any coat.)

Evangelista Torricelli found the horn in the 1640s. Slide the cutoff out to a million and watch the two totals.

Bottom: volume and surface area as the horn gets longerDrag the horn to turn it

1/2 + 1/4 + 1/6 + …

The leaning tower of books

Stack identical books at the edge of a table, each one sticking out past the one below. How far out can the top book reach? Work from the top down: the top book can stick out half its length past the second. The second can stick out a quarter past the third, the third a sixth past the fourth, and so on down to the table.

The steps keep shrinking, but together they make half of 1 + 1/2 + 1/3 + 1/4 + …, the harmonic series, and that sum grows forever. With 4 books the top one is entirely past the table. Reaching 2 book lengths out takes 31 books, 3 takes 227, and 10 would take about 272 million. With one book per layer, no stack reaches farther.

Drag a book to try to beat it. The markers show where everything above each book balances: exactly on its edge.

Markers: where the books above balance. Dashed: the table's edge.Drag a book sideways

Infinitely many pieces, one whole

Geometric series

Eat half a cake, then half of what's left, then half of that. The pieces never run out, yet you never eat more than one cake: 1/2 + 1/4 + 1/8 + … adds up to exactly 1. The square shows why. Each piece fills half of the gap that's left, so the gap shrinks to nothing.

Other pictures give other sums. Cut a triangle into four, color three of the pieces, and repeat in the top corner. Each color gets 1/4 + 1/16 + 1/64 + …, and the three colors share the triangle equally, so that sum is 1/3. In general, if each term is r times the last, 1 + r + r² + r³ + … = 1/(1 − r) for any r between 0 and 1.

Zeno of Elea argued that fast Achilles can never catch a slow tortoise: whenever he reaches where it was, it has moved on. There are infinitely many stages, but they shrink by r each time, so they add up to a finite distance. Turn on Zeno's clock to see why the argument feels so convincing.

Each new piece is r times the size of the lastPick a picture, then slide r
Picture

However thin the band

The limit game

What does it mean for f(x) to close in on L as x closes in on a? Make it a game. A skeptic picks a tolerance ε: a band reaching ε above and below L. You answer with a window δ around a, so that every x in the window (except a itself) puts f(x) inside the band. If you can always answer, however thin the band, the limit is L.

Here the game answers for you. sin x ÷ x isn't even defined at 0, yet it closes in on 1, and every band gets a window. Zoom in on x sin(1/x) and the wiggles never stop, but they're squeezed into the band. A jump is different: once ε is less than half the jump, no window is small enough, whatever L you choose. Drag L and try.

Augustin-Louis Cauchy and Karl Weierstrass turned this game into the modern definition of a limit in the 1800s.

Pink band: L ± ε. Grey window: a ± δ. Green stays in, pink escapes.Drag the L knob up and down
Function

Follow the dashes

Slope fields

A differential equation doesn't hand you a curve. It tells you how steep the curve must be at every point: y′ = y(1 − y) says that at height y the slope is y(1 − y). Draw that slope as a little dash everywhere and you get a slope field, a map of every solution at once.

Tap anywhere to drop a seed, and the curve through it is traced by following the dashes a tiny step at a time. Different seeds give different curves, but all of them obey the same rule. In logistic growth every positive start levels off at 1, the way a population levels off at what its home can feed. Drag a seed and watch its curve swing.

Pierre-François Verhulst proposed the logistic equation in 1838 to describe how populations grow.

Dashes: the slope at each point. Specks drift along the field.Tap to drop a seed, drag one to move it
Equation

Feeling your way to the bottom

Gradient descent

You're on a hillside in thick fog and want to reach the bottom. You can't see the valley, but you can feel which way the ground slopes under your feet. So take a step downhill, feel again, and repeat. That's gradient descent: the gradient points uphill, and each step goes the other way, scaled by a learning rate.

The rate is a balancing act. Too small and you creep. Too big and you overshoot, zigzagging from one side of the valley to the other, and past a certain size you fly off for good. Even done well, you can end up in a little dip that isn't the lowest point. Momentum helps: keep part of your last step, like a rolling ball, and you can coast over small ridges.

Augustin-Louis Cauchy described the method in 1847. Today it trains neural networks, nudging billions of numbers downhill at once.

Bright: high ground. Lines: equal height. Arrow: the next step.Tap the map to drop the ball, or drag the ring
Landscape

1 + 1/4 + 1/9 + 1/16 + …

The Basel problem

Add up one over every square number: 1 + 1/4 + 1/9 + 1/16 + … The terms shrink fast enough that the total settles down, and you can see it never passes 2. Draw each term as a square of that area, with side 1/n. Put the squares with sides 1/2 and 1/3 in a row, then 1/4 to 1/7, then 1/8 to 1/15, and so on. Every row is less than 1 wide, and the rows are 1/2, 1/4, 1/8, … tall, so they all fit in a 1 × 2 box.

But what is the total? Pietro Mengoli asked in 1650, and for decades the best mathematicians in Europe couldn't say. In 1734 Leonhard Euler, born in the Swiss city of Basel, showed that it's exactly π²/6 ≈ 1.6449. Nobody expected π, the number of circles, in a sum about whole numbers.

The total creeps up slowly: after n terms it's still about 1/n short. Euler couldn't add a million terms by hand, so he estimated what was left over. Turn on Euler's shortcut to see how well that works.

Left: a square of area 1/n² for each n. Right: the running total.Dashed boxes: rows 1/2, 1/4, 1/8 … tall

Points between points

Bézier curves

Pick a few control points and join them in order. Walk the same fraction t of the way along each segment and join those new points. Do it again, and again, until a single point is left. As t runs from 0 to 1, that last point draws a smooth curve.

This recipe is de Casteljau's algorithm. The curve starts at the first point and ends at the last, and the points in between pull it toward them without the curve ever touching them. Three points make a quadratic curve, four a cubic and five a quartic: each extra point adds one more level of in-betweens.

Paul de Casteljau at Citroën and Pierre Bézier at Renault worked these curves out around 1960 to describe the shapes of car bodies. Today the letters of nearly every font on your screen are outlined with quadratic or cubic Bézier curves.

White: the curve so far. Colors: each level of in-betweens.Drag the numbered points
Control points

Hang a chain, build an arch

The catenary

Hold a chain by its two ends and let it hang. The curve looks like a parabola, and Galileo thought it came close to one. It isn't one. In 1691 Leibniz, Huygens and Johann Bernoulli found the true shape, the catenary: the graph of cosh x = (eˣ + e⁻ˣ) ÷ 2, stretched to fit.

The chain here is 60 links that know only two things: gravity pulls them down, and each link keeps its length. Left alone, it settles right onto the cosh curve. A parabola of the same length through the same ends fits a shallow chain well, but a deep one shows the gap. The parabola answers a different question: the shape of a cable holding up a level road, as on a suspension bridge.

Turn the chain upside down and every pull becomes a push. An arch in that shape stands under its own weight without bending. Robert Hooke put this as a riddle in the 1670s, and Gaudí designed buildings by hanging weighted strings and looking at them upside down.

Pink: cosh. Dashed: a parabola with the same ends and length.Drag the ends, or grab the chain

Chase the next one

Pursuit curves

Put a bug on each corner of a square. All at once, each starts walking toward the next bug around, always heading straight at it as it moves. The four of them stay on the corners of a square that shrinks and turns, and they spiral in to meet at the center.

How far does each one walk? Each bug walks at right angles to the bug chasing it, so the chaser closes the gap at its full speed. The gap starts at one side, so each bug walks exactly one side. On a triangle they walk two thirds of a side, and on a hexagon two whole sides. For n bugs it's side ÷ (1 − cos(360° ÷ n)).

Each path is a logarithmic spiral. It winds around the center infinitely many times, yet it has a finite length and the bugs arrive in a finite time. Édouard Lucas asked this puzzle about three dogs in the 1870s.

Faint lines: who was chasing whom, as the gaps shrinkDrag a bug to change the start
Bugs

Curves from straight lines

String art

Hammer pegs at even steps along two edges and join them with threads, in order: as one end of the thread moves toward the corner, the other moves away from it. Every thread is straight, yet a smooth curve appears where they cross. That curve touches every thread once, and it's called their envelope. Here it's a parabola, whatever the angle of the corner.

Other families of lines do the same. A ladder sliding down a wall wraps a curve called an astroid, even though the ladder's middle moves along a plain circle. Mark a dot inside a paper circle and fold the rim onto the dot, again and again: the creases wrap an ellipse whose two foci are the center and the dot. Fold a straight edge onto a dot and the creases wrap a parabola.

Mary Everest Boole, a teacher and the wife of the logician George Boole, came up with curve stitching in the 1800s so children could feel geometry with a needle and thread.

Violet: the thread, ladder or fold being added nowDrag the white points
Make it with

Straight lines out of circles

The Tusi couple

Roll a circle around the inside of a circle twice its size. Every point on the rim of the small circle slides back and forth along a straight line, a diameter of the big one. Each dot here stays on its own line the whole time.

Put several dots on the rim and together they look like a ring that turns and wobbles, yet none of them ever leaves its line. Move the dots in from the rim and the lines open up into ellipses. Two opposite dots slide along crossed lines, like the two pegs of the trammel carpenters use to draw ellipses.

The Persian astronomer Nasir al-Din al-Tusi described the trick in the 1200s, to build back-and-forth motion out of the perfect circles that astronomy then allowed. Copernicus used the same device in his great book of 1543.

Faint lines: the track each dot followsDrag the small circle to roll it by hand
Dots

Equal areas, equal times

Kepler's laws

Launch a planet around the sun by dragging the arrow: its length is the speed and its direction is the aim. At just the right speed the planet circles. A little faster or slower and the circle stretches into an ellipse. Past √2 times the circling speed, it escapes and never comes back.

Johannes Kepler found three rules hiding in Tycho Brahe's measurements of the planets, and published them in 1609 and 1619. Orbits are ellipses with the sun at one focus. The line from the sun to the planet sweeps out equal areas in equal times, so a planet speeds up near the sun. And the square of the time for one orbit grows like the cube of the orbit's size: T² ∝ a³.

Each shaded slice here takes the same time, and they all have the same area. Newton showed in 1687 that all three rules follow from one pull that weakens with the square of the distance. In the chart, your orbit lands on the same line as the eight planets.

Distances in AU (Earth to sun), times in yearsDrag the arrow tip or the launch point
Launch

Two blocks and a wall

Counting π with collisions

A small block sits between a wall and a big block sliding toward it. There's no friction, and every bounce is perfect. Count the clacks, block on block and block on wall. If the two blocks weigh the same, you hear 3. Make the big one 100 times heavier and you hear 31. At 10,000 times, 314. At a million times, 3141.

Why π? Take the two speeds, each multiplied by the square root of its block's mass. Energy never changes, so that pair always lands on a circle, drawn below the blocks. Each clack is a straight jump to a new point on the circle, and the jumps turn by the same small angle each time. The clacks stop once those angles add up to half a turn, π. With a mass ratio of 100ⁿ the angle is almost exactly 1 ÷ 10ⁿ, so the count is π's first n + 1 digits.

Gregory Galperin published this in 2003. It's a gloriously slow way to find π: every extra digit needs a block 100 times heavier and 10 times as many clacks.

Below: the two speeds, scaled by √mass, always on one circlePick how heavy the big block is
Big block to small block

When waves meet

Ripples and interference

Drop two pebbles into a pond and their ripples run through each other. Where a crest meets a crest the water rises twice as high. Where a crest meets a trough they cancel, and the water stays still. The still places form dark lines fanning out from between the two sources.

Every point on a dark line is half a wavelength (or 1½, or 2½…) further from one source than from the other, so the two waves always arrive out of step there. Curves like that are hyperbolas. Move the sources apart or shorten the waves, and more dark lines appear.

In the early 1800s Thomas Young sent light through two narrow slits and saw stripes of light and dark on the far wall: the same pattern, and strong evidence that light is a wave. Switch to the double slit to see the stripes form.

Amber crests, blue troughs, dark where the waves cancelDrag the sources. Point anywhere to compare paths.
Setup
Show

Sand on a singing plate

Chladni figures

Sprinkle sand on a thin metal plate, then draw a violin bow down one edge. At certain notes the plate rings, and the sand dances off the parts that shake and piles up along lines that stay perfectly still. Every note has its own pattern.

The still lines are where the plate's standing wave has no movement at all. On a square plate, each pattern here is a good approximation made by mixing two waves: one with m ripples across and n down, the other with n across and m down. The sand settles where the two cancel. Bigger numbers mean higher notes and finer patterns.

Ernst Chladni showed these figures around Europe in the years near 1800. Napoleon was so impressed that he had the French Academy offer a prize for the mathematics behind them, and Sophie Germain won it in 1816.

Sand gathers on the lines that stay stillTap the plate to knock sand loose
Mix the two waves

Music from one string

Standing waves on a string

Pin a string at both ends and it can only swing in certain ways: one big arch, or two arches with a still point between them, or three, and so on. These are its modes. A whole number of arches has to fit between the ends, so mode 2 vibrates twice as fast as mode 1 and mode 3 three times as fast.

Pluck the string and it plays many modes at once, which is why a guitar note sounds rich rather than pure. Neighboring modes make the intervals of music: 2 to 1 is an octave, 3 to 2 a fifth, 4 to 3 a fourth and 5 to 4 a major third. Pluck exactly in the middle and every even mode goes missing, since each one has a still point there. Pluck a third of the way along and modes 3, 6, 9… vanish.

Pythagoras is said to have found that half a string sounds an octave higher. In the 1750s Daniel Bernoulli argued that every vibration of a string is a sum of these modes.

Bars: how much of each mode is in the motionDrag the string to pluck it
Show

Five ways to put things in order

The sorting race

Every lane starts with the same shuffled bars, and each one sorts them its own way. The race is fair: in each step, every lane gets to compare two bars or make one move, and nothing else.

Bubble and insertion sort only ever swap neighbors, so a bar that's far from home has to crawl there one place at a time. Their work grows with the square of the number of bars. Merge, quick and heap sort split the job into halves, and their work grows like n × log₂ n instead. For 100 bars that's one or two thousand steps against five to seven thousand, and the gap keeps widening.

Can anyone do better? Not by much. There are n! ways to shuffle n bars, and one comparison can at best rule out half of them. So any method that only compares needs at least log₂(n!) comparisons in the worst case, which is 525 for 100 bars. Try Reversed and Nearly sorted to see which methods notice order that's already there.

White: being compared. Pink: being moved.With Sound on, click a lane to listen to it
Start with
Bars

Carving a maze

Mazes

Start with a grid where every cell is walled in, and knock down walls until every cell can be reached. If you never open up a loop, you get a perfect maze: exactly one path joins any two cells. In the language of graphs, it's a spanning tree of the grid.

How you knock the walls down gives each maze its character. The backtracker tunnels as far as it can and backs up only when it's boxed in, which makes long winding corridors. Prim's method grows the maze outward from random spots on its edge, which makes lots of short dead ends. Wilson's method wanders at random and erases every loop it makes. It starts painfully slowly, but it's perfectly fair: every possible maze is equally likely.

To escape a perfect maze, keep your right hand on the wall and walk. You can't go around in circles, because there are no circles to go around. Or fill in the dead ends one by one, until only the way out is left.

Green: start. Pink: the exit. Gold: the only way through.Click any cell to move the exit
Carve with
Solve by
Size

Finding the way

Shortest paths

Three ways to get from the green dot to the pink one. Breadth-first search spreads out evenly, one ring of cells at a time, so it finds the route with the fewest steps. But it can't tell mud from road, and here mud costs 5 times as much to cross.

Dijkstra's algorithm, from 1956, always grows from the cheapest cell reached so far, so it finds the cheapest route. It still searches in every direction, even away from the goal. A*, from 1968, adds a guess of the distance still to go: the number of steps if there were no walls. The guess is never too big, so A* still finds the cheapest route, and it usually explores far fewer cells.

Draw walls and mud, drag the dots around and compare the counts. Game characters find their way around this way, and so, with much bigger maps and cleverer guesses, do route planners.

Color: cells explored, in order. Brown: mud. Gold: the route.Draw on the grid. Drag the dots.
Search
Draw
Map

The shortest round trip

The travelling salesperson

Visit every city once and come home, by the shortest route. With 5 cities there are only 12 different round trips to compare. With 20 there are about 61 thousand trillion, and checking a billion a second would take almost two years. Each extra city multiplies the count again.

Nobody knows a fast method that always finds the best trip, and most mathematicians suspect there isn't one. So in practice you settle for a good one. Nearest neighbor always drives to the closest city it hasn't visited: quick, but it paints itself into corners. 2-opt keeps swapping two roads for two shorter ones, which untangles every crossing. Simulated annealing makes random swaps and also accepts some that make the trip worse, less and less often as it cools, so it can shake itself out of a bad route.

Click to add cities and drag them around. With 12 or fewer, the readout also shows the shortest trip there is, worked out by a much cleverer method than checking every trip, so you can see how close the quick methods get.

The colors run once around the trip. Dashed: the shortest one.Click to add a city, drag to move one
Method
New cities

Stretching a rubber band

The convex hull

Hammer nails into a board, stretch a rubber band around all of them and let go. It snaps onto the convex hull: the smallest shape with no dents that holds every nail. A computer has no rubber band, so it has to work out which points are on the outside.

Gift wrapping starts at the leftmost point and swings a line around until every other point lies on one side of it, then does the same from where it landed. With n points and h of them on the hull, that's about n × h tests: quick when few points are on the outside, slow when many are. Graham scan first sorts the points by angle, then walks around once, keeping left turns and throwing out any point where the path turns right. Its cost is mostly the sorting, which grows like n log n.

Drag the points, or click to add more. Pick Ring, where nearly every point is on the hull, and watch gift wrapping slow down.

Green: on the hull. Pink dash: a right turn, so a point is thrown out.Drag a point, or click to add one
Method
Scatter

A puzzle from 1883

The Towers of Hanoi

Move the whole tower to the last peg. You may move one disk at a time, and a disk may never sit on a smaller one. Édouard Lucas sold the puzzle as a toy in 1883, with a legend about priests moving a tower of 64 golden disks.

The trick is to think recursively. To move n disks, move the top n − 1 out of the way, move the biggest disk, then move the n − 1 back on top of it. Each new disk doubles the work and adds one, so n disks take 2ⁿ − 1 moves, and no method does it in fewer. At one move a second, the priests' 64 disks would take about 585 billion years.

Watch the binary counter under the pegs. Count from 1 to 2ⁿ − 1 in binary, and on each count the disk to move is the one whose bit just turned from 0 to 1. So the smallest disk moves on every odd count, always the same way around.

Counter: one bit per disk, the smallest on the rightPlay by hand: click a peg to lift its top disk, then click where it goes
Who moves

Backtracking

The n queens puzzle

Put 8 queens on a chessboard so that no two attack each other: no two share a row, a column or a diagonal. There are about 4.4 billion ways to place 8 queens on the board, and only 92 of them work. Count rotations and mirror images as the same and there are just 12.

Backtracking finds every one without trying them all. Put a queen on the first safe square of the next row. If a row has no safe square left, go back up a row and move that queen along. Each dead end cuts off a whole branch of possibilities at once, so the search for all 92 checks only 15,720 squares.

The chess player Max Bezzel posed the puzzle in 1848. Nobody has found a formula for the number of solutions. Bigger boards have been counted only by huge computer searches. The solutions for 27 queens were counted in 2016.

Shaded: squares attacked by the queens aboveRed: a square under attack, so the search moves on

Error-correcting codes

The Hamming code

Send 4 bits of message plus 3 check bits. Each check bit is chosen so that its circle holds an even number of 1s. Now let noise flip any one of the 7 bits. Some circles turn odd, and together they point at exactly one spot: the bit that flipped. Flip it back and the message is repaired, without asking for it to be sent again.

It works because each of the 7 positions sits inside a different set of circles, so every possible mistake leaves a different fingerprint. Number the positions 1 to 7 and it gets better: give the circles the values 1, 2 and 4, and the odd ones add up to the position of the bad bit. Flip two bits, though, and the circles are fooled into pointing at a third.

Richard Hamming came up with the code in the late 1940s, fed up with a Bell Labs computer that gave up on his weekend jobs whenever it found an error. Codes built on his idea still guard computer memory. Switch to Message to send words down a noisy line, with and without the code.

Each circle should hold an even number of 1s. Pink outline: a flipped bit.Tap any bit to flip it
Show

A game solved in binary

Nim

Take turns removing stones. On your turn, take as many as you like from one row, but at least one. Whoever takes the last stone wins. It feels like a game of hunches, but in 1901 Charles Bouton worked out exactly who wins from any position, and how.

Write each row's size in binary and add the columns without carrying: a column with an odd number of 1s gives a 1, an even number gives a 0. That's the nim-sum. If it's 0 on your turn, every move you make breaks the 0, and your opponent can always put it back. If it isn't 0, some move makes it 0, and that's the move to make. The last stone leaves a nim-sum of 0, so whoever keeps making zeros takes it.

The computer knows this. Start with 3, 4 and 5 stones and go first: you can win, but only if you keep finding the zero. Start with 1, 3, 5 and 7 and the first player loses against perfect play.

Right: each row in binary, with the nim-sum underneathTap a stone to take it and every stone to its right
Rows
Who starts
Computer

Trust, tested by computer

The prisoner's dilemma

Two players each choose to cooperate or to defect. If both cooperate they get 3 points each, and if both defect they get 1 each. If one defects on a cooperator, the defector gets 5 and the cooperator gets nothing. Whatever the other player does, defecting pays more. Yet two defectors end up worse off than two cooperators.

Play the same opponent again and again, and things change. Around 1980, Robert Axelrod ran two computer tournaments where strategies sent in by experts played each other for many rounds. Both times the winner was one of the simplest entries: tit for tat, sent in by Anatol Rapoport. It cooperates first, then copies whatever its opponent did last. It's never the first to defect, it hits back at once, and it forgives at once.

Who comes out on top depends on who else is playing, so switch strategies on and off. In Evolution, strategies that score well take over more of the population. Starting with many pushovers, always defect booms at first, then starves once they're gone. Add mistakes and watch revenge echo back and forth.

Each square: the row's average points a round against the columnTap a square to see that match. Dots: green cooperate, pink defect.
Show