I was bored so I thought I’d write a PHP script to generate fractals (like you do). The Mandlebrot set is probably the most well-known fractal so I chose to write a script to generate fractals using the Mandlebrot set:

This is a 500×500 fractal plotted for x (real) values between -1.5 and 0.5 and y (imaginary) values between -1 and 1.

#### How it Works

The mathematics behind the mandlebrot set involve:

- complex numbers (x+yi)
- quadratics
- argand diagram
- limits

A complex numbers consists of a real component and an imaginary component. i is the square root of -1. A complex number could look like 3+2i, where 3 is the real component and 2 is the imaginary component.

An argand diagram is like a two dimensional number line. With normal real numbers, we can plot them on a one dimension number line, with negative infinity on one end, and positive infinity on the other end. Because complex numbers have an imaginary component too, we need a two-dimensional plane to plot the number.

The Mandlebrot set involves iterating through a sequence:

In words: the first value in the sequence is 0. To find the next value in the sequence, we square the current value and add the complex number (which is the variable). Depending on the input, the sequence will either tend towards infinity or it will remain bounded and oscillate/repeat. If the sequence remains bounded, then it is inside the Mandlebrot set. On my script, I’ve marked these pixels as black.

For those values outside the Mandlebrot set, we use colour to denote how long it takes to reach infinity (in fact we use a shortcut and stop when |z| > 2).

Quadratics come in when we square a complex number – you can just square them as you would with any other quadratic. However, i^2 = -1.

#### Conclusion

I think it’s pretty amazing how we can generate infinitely complex patterns using such simple mathematics. There is probably only about 10 lines of mathematics in the script; the rest is all PHP/image stuff.

A few notes:

- The script is pretty server intensive. The source code I’ve provided is configured to produce a 100×100 image by default. This took 2 minutes to execute on my machine, but 5 seconds on my friends machine. Both of them are roughly the same spec. Your mileage may vary.
- If you try to generate an image with too many pixels, your PC may crash. You have been warned ðŸ™‚
- Try changing the x/y min/max values to zoom or to pan.
- Feel free to hack the script, rip it apart or do whatever you want with it. It’s public domain.