Mandelbrots and Pi

Created 28th January, 2010 04:55 (UTC), last edited 28th January, 2010 05:50 (UTC)

I'm sure everybody who has ever played around with computer programming has at one point or another written some code that draws the Mandelbrot set. It turns out that there's a cool way to calculate π in there too.

The Mandelbrot

If you've not implemented complex numbers before they're fairly simple. A complex number is a binary tuple where the first number is real and the second imaginary, (x, yi). i is the square root of -1. Squaring these numbers is fairly simple:

let sqc (r, i) = ( r * r - i * i, 2 * r * i )

And adding them is even simpler:

let add (r1, i1) (r2, i2) = (r1 + r2, i1 + i2)

The basics of the sequence are to convert the x and y screen position into a complex number over the range -1 to 1 on each axis and then keep squaring and adding:

let step o v = add o (sqc v)

Where o is the original number and v is the result of the last iteration step. The steps are always started with a point at the origin, so at step 0 the value is 0, and at step 1 the value is the complex number we're calculating for.

The normal way to determine if a given location is outside the Mandelbrot is to keep doing the calculation step until the distance from the origin is more than 2 — once we're more than 2 away from the origin then we know that the calculation will keep producing ever bigger numbers. Inside the set the iteration will never complete as the calculation goes into an infinite loop. The distance from the origin is done in the obvious way using Pythagoras' theorem (but now we're not taking the y as a complex number, it's simply a distance along the axis):

let length (r, i) = sqrt (r * r + i * i)

Calculate π

The calculation involves using complex numbers where the real component is -0.75 and is really simple. You decide how accurately you want to calculate π, say we want ±0.2 (the error term), we then do the steps from the Mandelbrot counting how many steps we need until the distance goes to 2 or more. π is the number of steps times our error term takes to get to a distance of 2 or more.

Doing the calculation we get 15 steps so π is 15 × 0.2 ±0.2. We can reduce the error term to get more accurate results.

So, go away and have a play, get some values of π and see how long it takes to calculate