Algorithms

Barnsley fern: four rules draw a leaf

Start with a single point. At each step, choose one of four rules, calculate the new position and plot it. After a few thousand steps, the stem and side parts emerge from the point cloud. Scrub through the construction to see the shape appear, and use colour to tell which rule produced each point.

Start: (0, 0). First 12 points: one per step, then up to 200. A new setup restarts playback; changing colour keeps the current step.

f1 · Stem · 1%
Points: 0
f2 · Main part · 85%
Points: 0
f3 · Left part · 7%
Points: 0
f4 · Right part · 7%
Points: 0

Plotted points: 0. Current point: (0.0000, 0.0000).

Choose Next to inspect the first transformation.

The count includes repeated points, but excludes the initial (0, 0). Rule percentages are selection probabilities; the counters show actual choices in this run.

Video walkthrough

The chaos game with four new rules

In the chaos game, each step moved halfway towards a randomly chosen triangle vertex. The fern follows the same idea, but we choose a formula for the new coordinates instead of a vertex. The formulas define affine maps. Together they form an iterated function system, or IFS.

At each step, the chosen rule maps the current point to the next one. The following step uses those coordinates and the state of the random number generator. Every plotted point stays on the drawing. Their positions form the silhouette of the fern.

Four transformations

Each rule calculates the pair (x′, y′) from the previous coordinates (x, y). The table shows how likely each rule is to be chosen and how it changes the coordinates.

Rule f₁ sets x to zero and scales y down, placing its points on the vertical axis near the base of the stem. Applying f₂ to every point would shrink, slightly rotate and lift the pattern to form the main part of the leaf. In the same way, f₃ and f₄ give the lower left and right parts. Each construction step applies its chosen rule to the current point alone.

Classic Barnsley fern: both coordinates use the old point
RuleProbabilityx′y′
f₁1%00.16y
f₂85%0.85x + 0.04y−0.04x + 0.85y + 1.6
f₃7%0.20x − 0.26y0.23x + 0.22y + 1.6
f₄7%−0.15x + 0.28y0.26x + 0.24y + 0.44

Why one rule is chosen more often

First the generator produces a number r in the range 0 ≤ r < 1. If r < 0.01, choose f₁. Otherwise check the next threshold, 0.86, for f₂, and then 0.93 for f₃. Everything left goes to f₄. The lengths of the four intervals give weights of 1%, 85%, 7% and 7%.

Rule f₂ has the widest interval, so it is chosen most often. The counters below the drawing show how often each rule was used in the current run. In a hundred steps, f₂ may be chosen more or fewer than 85 times. Adjusting the weights affects the density of the plotted points. With positive weights for all four rules, the limiting shape stays the same.

Check the first two steps by hand

With seed 42, the first two choices are both f₂. From (0, 0), we get x′ = 0 and y′ = 1.6. On the second step, x′ is 0.04 × 1.6 = 0.064, and y′ is 0.85 × 1.6 + 1.6 = 2.96. Both formulas use the same previous coordinates, x = 0 and y = 1.6.

The player shows the first 12 points one at a time. The dashed segment marks the move from the previous point to the new one. After that, each playback step adds up to 200 points. The total counts every application of a rule, including repeated coordinates. Counting begins with the first point calculated after the start.

Why the shape repeats

All four maps bring points closer together. Apply any one of them to two distinct points, and the distance between those points will decrease. Together the maps define a limiting shape called an attractor.

Call the attractor A. Apply each rule to the whole of A separately, then take the union of the four results. This gives back the original set A. In symbols, A = f₁(A) ∪ f₂(A) ∪ f₃(A) ∪ f₄(A).

The parts of the attractor are contracted images of the whole. Some maps change the proportions, and f₁ puts all the points on the vertical axis. This property is called self-affinity. A cloud of a few thousand points approximates the shape. Adding more points reveals finer details.

Random choices you can repeat

The seed is the starting number for a 32-bit pseudorandom number generator. The same seed gives the same sequence of rule choices. If you request more points with the same seed, the new sequence starts with all the points from the previous run.

The Another sequence button changes the seed and starts the construction again. A different seed produces different coordinates, and enough points bring out the same silhouette. The shareable link keeps your settings, position on the timeline, speed and colouring choice.

Time and memory

Generating n points takes O(n) time. Plotting each point as it is generated needs O(1) extra memory for the current coordinates and generator state. The function below collects the points in an array, so its result occupies O(n) memory.

The player stores a single array of points. Each frame on the timeline records how many points to show from the start of the array. This allows seeking with O(n) total memory. Preparing and drawing a frame with k points takes O(k).

Construction code

This code uses the same coefficients, selection thresholds, generator and starting point as the interactive. Each record holds the new coordinates and a rule index. The indices 0 to 3 correspond to rules f₁ to f₄.

Show executable code
function barnsleyFern(seed = 42, count = 20000) {
  if (!Number.isInteger(seed) || seed < 0 || seed > 0xffffffff ||
      !Number.isInteger(count) || count < 1 || count > 50000) {
    throw new Error("Invalid input");
  }
  // [a, b, c, d, e, f]: x' = a*x + b*y + e; y' = c*x + d*y + f
  const maps = [
    [0, 0, 0, 0.16, 0, 0],
    [0.85, 0.04, -0.04, 0.85, 0, 1.6],
    [0.2, -0.26, 0.23, 0.22, 0, 1.6],
    [-0.15, 0.28, 0.26, 0.24, 0, 0.44]
  ];
  let x = 0, y = 0, random = seed;
  const dots = [];
  for (let i = 0; i < count; i++) {
    random = (Math.imul(1664525, random) + 1013904223) >>> 0;
    const r = random / 4294967296;
    const rule = r < 0.01 ? 0 : r < 0.86 ? 1 : r < 0.93 ? 2 : 3;
    const [a, b, c, d, e, f] = maps[rule];
    const nextX = a*x + b*y + e;
    const nextY = c*x + d*y + f;
    x = nextX;
    y = nextY;
    dots.push({ x, y, rule });
  }
  return dots;
}

Things to try

Choose “12 points · inspect” and use Next to take a few steps. Below the drawing, you can see which rule was used and how both new coordinates were calculated. Then choose “20,000 points · fern”, click Show results and use the timeline to revisit earlier frames. The scale stays the same throughout.

Compare the drawing with Colour by rule turned on and off. Find the two lower side parts. Keep the seed, increase the point count to 50,000 and click Show results again to compare the density. Then try another seed with the same point count.

Sources

Explore next

Chaos game and the Sierpiński triangle

Pythagoras tree

Dragon curve