Python - Make Your Own Mandelbrot Set PDF
Python - Make Your Own Mandelbrot Set PDF
T
he image below depicts the famous code files and using shells to execute the programs.
WHY DO THIS? Mandelbrot set. You may have seen it on You can also share your web-based “notebooks” by
• Create hugely complex posters, music videos or demonstrations of exporting them, or sharing them online.
results from a simple
equation. computer power – back in the 1990s it took hours to There are pre-packaged distributions of IPython
• Turn this into pretty plot it using home computers. Despite its organic including the numerical and graphical extensions, so
graphs! intricate appearance it is in fact the result of extremely you don’t have to worry about installing and
simple mathematics. configuring the right versions and their many
The maths hasn’t changed since the 1990s, but dependencies. Even better, because IPython is used
computing power has come on in leaps and bounds, purely through a web browser, you can use one of
so the psychedelic beauty of the Mandelbrot set can several online services offering IPython in the cloud.
be ours to play with. We’ll be using the Python You don’t have to install any software at all, and you
programming language because it’s popular, easy to can work on your code and demonstrate the results
learn, and has well established numerical and plotting from any internet-connected device that supports a
extensions. It’s no accident that Python is the tool of modern browser.
choice in the scientific community, as well as The code in this article series was tested with the
powering some of the world’s largest infrastructures. online service from wakari.io, which offers free trial
The following images
As an interpreted, rather than compiled language, accounts, and the locally installed IPython Anaconda
are closeups of parts of
this same fractal. The Python gives immediate feedback. We’re going to take free distribution from continuum.io.
Mandelbrot set is in fact this interactivity one step further by using IPython, Whether you select an online service or install your
infinitely detailed, and which is Python packaged with an interactive web own IPython distribution, check to see if it works by
contains a wide variety of interface. You can just type instructions and get firing it up and clicking on New Notebook. Type 2*3
patterns. results straight away. You avoid having to edit source into it and click the Run button, which looks like an
audio play selector. If it responds with ‘6’, great – you
have a working IPython environment!
Beginning Python
Let’s now learn just enough Python to make our own
Mandelbrot fractal. Fire up IPython and open a new
notebook. In the next ready cell, labelled In [ ], type the
following code and click Play (or press Ctrl+Enter).
print “Hello World!”
You should get a response that simply prints the
phrase “Hello World!” You should see that issuing the
second instruction didn’t remove the previous cell with
its instruction and output answer. This is useful when
you’re slowly building up a solution of several parts.
The following code introduces the key idea of
variables. Enter and run it in a new cell. If there is no
new empty cell, click the button with the downward
pointing arrow labelled ‘Insert Cell Below’, not to be
confused with the one labelled “Move Cell Down”.
x = 10
print x
print x+5
print z
The first line, x = 10, looks like a mathematical
statement that says x is 10. In Python this means that
x is set to 10, that is, the value 10 is placed in an
virtual box called x. That 10 stays there until further
96 www.linuxvoice.com
MANDELBROT & PYTHON CODING
Fractals
Before we dive in and start coding, let’s take a is entirely random noise – there isn’t a lack of patterns with just the right amount of unpredictable
step back and consider again some of the patterns detail, but now there isn’t enough structure in the variation. These patterns are called fractals.
we find in nature or create ourselves. Look at the image to keep us interested. The cauliflower has The Mandelbrot fractals appear natural, organic
following three images. repeated patterns at different scales. These and even beautiful because they too sit at that fine
The first set of shapes is very regular. They’re patterns also have just the right amount of variation line between order and chaos, having structures
what most people would consider mathematical to keep us interested. This is a common theme that have self-similar patterns but infused with just
shapes, but there isn’t enough interesting detail in throughout nature, where clouds, mountains, rivers, enough variation – and parts of these fractals do
them to hold our attention for long. The last image trees, blood vessels etc all have self-similar look like plants, lightning or natural coastlines.
notice. We shouldn’t be surprised that print x prints in is the bit that creates a loop, and here it does
the value of x, which is 10. Why doesn’t it just print x? something for every number in the list, and keeps
Python will evaluate whatever it can, and x can be count by assigning the current value to the variable n.
evaluated to the value 10, so it prints that. The next We saw variables earlier, and this is just like assigning
line, print x+5 evaluates x+5, which is 10+5 or 15, so n=0 during the first pass of the loop, then n=1, then
we expect it to print 15. n=2, until n=9, the last item in the list.
What happens with the line print z when we haven’t The next line print n prints the value of n, just as
assigned a value to it like we have with x? We get an before. We expect all the numbers in the list to be
PRO TIP
error message telling us about the error of our ways, printed. But notice the indent before print n. This is Explore the Mandelbrot
fractal using the
trying to be helpful as possible so we can fix it. important in Python as indents are used meaningfully interactive XaoS open
to show which instructions are subservient to others, source software at
Automating lots of work in this case, the loop created by for n in .... The loop http://bit.ly/1vLdz52 or
through a web browser
Computers are great for doing similar tasks many ends when the code stops being indented. Here, we’ve http://bit.ly/1lbXYL1.
times – they don’t mind and they’re very quick used a pass instruction to highlight the end of the loop
compared with humans with calculators. Let’s see if (pass is superfluous, and Python will ignore it but it
we can get a computer to print the first 10 squared helps the interpreter exit a code block. You can remove
numbers, starting with 0 squared, 1 squared, then 2 it if you want). This means we only expect done to be
squared and so on. We expect to see a printout of printed once, and not 10 times.
something like 0, 1, 4, 9, 16, 25, and so on. Issue the It should be clear now that we can print the squares
following code into the next ready cell and run it. by printing n*n. In fact we can make the output more
range(10) helpful with phrases like “The square of 3 is 9”. The
You should get a list of 10 numbers, from 0 up to 9. following code shows this change inside the loop.
This is great because we got the computer to do the Note how the variables are not inside quotes and are
work to create the list – we didn’t have to do it therefore evaluated.
ourselves. for n in range(10):
A common way to get computers to do things print “The square of”, n, “is”, n*n
repeatedly is by using loops. The word loop does give pass
you the right impression of something going round print “done”
and round potentially endlessly. Rather than define a This is already quite powerful. We can get the
loop, it’s easiest to see a simple one. Enter and run computer to do a lot of work very quickly. We could
following code in a new cell. easily make the number of loop iterations much larger
for n in range(10): by using range(100) or even range(100000) if we
print n wanted. Try it!
pass
print “done” Functions
There are three new things going on here. The first Python makes it easy to create reusable computer
line has the range(10) command that we saw before, instructions. Like mathematical functions, these
which creates a list of numbers from 0 to 9. The for n reusable snippets of code, also called functions, stand
www.linuxvoice.com 97
CODING MANDELBROT & PYTHON
The simple folk of the 90s would be awed and terrified to see the Mandelbrot set calculated in a browser.
98 www.linuxvoice.com
MANDELBROT & PYTHON CODING
Arrays
Arrays are just tables of values. You refer to particular
cells with the row and column number, just like you
would with cells in a spreadsheet.
Enter and run the following code.
a = zeros( [3,2] )
print a
This creates an array of shape 3 by 2, with all the
cells set to the value zero and assigns the whole thing
to a variable named a. Printing a shows the array full
of zeros in what looks like a table with three rows and
two columns.
Now let’s modify the contents of this array. The
following code shows how you can refer to specific
cells to overwrite them with new values. It’s just like
referring to spreadsheet cells or street map grid
references.
a[0,0] = 1
a[0,1] = 2
a[1,0] = 9
a[2,1] = 12 An example of the images
print a doing just this. produced by the code
The first line updates the cell at row zero and print a[0,1] teaser, below. Can you
column zero with the value 1, overwriting whatever v = a[1,0] figure out how it works?
was there before. The other lines are similar updates, print v
with a final printout. Remember that the column and row numbering
Now that we know how to set the value of cells in starts from 0 and not 1, so the top-left is at [0,0] not
an array, how do we look them up without printing out [1,1]. This also means that the bottom-right is at [2,1]
the entire array? We’ve been doing it already. We not [3,2].
simply use the expressions like a[1,2] or a[2,1] to refer
to the content of these cells. The code shows us Plotting arrays
PRO TIP
Visualising arrays graphically is sometimes more
Remember that in
insightful than looking at large tables of numbers. We Python, indents have
can think of them as flat two-dimensional surfaces, meaning. Instructions
coloured according to the value at each cell in the that are subservient to
another are indented.
array. Let’s plot the small 3 x 2 array we created above: This includes function
imshow(a, interpolation=”nearest”) definitions and the
The instruction to create a plot is imshow(), and the contents of loops. An
errant space or tab can
first parameter is the array we want to plot. That last cause hard-to-spot errors.
bit, interpolation, is there to tell Python not to try to
blend the colours to make the plot look smoother,
which it does by default. The output is shown in the
image below.
As a teaser of things to come, the following short
PRO TIP
code will plot different images every time you run it.
Experiment with the
See if you can work out how it works using the online imshow() function
Python documentation. by trying different
import numpy as np options explained in its
documentation at
figsize(5,5) http://bit.ly/1lu1mkB.
imshow(np.random.rand(10,10), interpolation=”lanczos”)
The array cells which have the same value also have the To really appreciate the Mandelbrot fractal we need
same colour. When we plot the Mandelbrot set, we’ll be to experience for ourselves the unexpected behaviour
using this very same imshow instruction. of very simple mathematical functions that lead to
www.linuxvoice.com 99
CODING MANDELBROT & PYTHON
100 www.linuxvoice.com
MANDELBROT & PYTHON CODING
www.linuxvoice.com 101
CODING MANDELBROT & PYTHON
Subtract the complex number (c + di) from (a + bi) (a + bi) - (c + di) = (a-c) + (b-d)i
Subtract the real and imaginary parts independently.
Multiply the two complex numbers (a + bi) * (c + di) (a + bi) * (c + di) = (ac + adi + bci + dbi2) = (ac-bd) + (ad+bc)i
Expand out the terms and apply the special rule that i2 is -1.
Then collect real and imaginary parts to make a neat answer.
value of iteration. If the point doesn’t diverge, then x_list = linspace( -2.0, 4.0, 13)
abs(z) is never more than 4, so the for loop simply y_list = linspace( -2.0, 2.0, 9)
keeps running until the count reaches the maximum for x in x_list:
iterations, and it is this maximum that is then finally for y in y_list:
returned by the mandel(c, maxiter) function. print x,y
pass
The atlas pass
We now need to define in Python which part of this Next we need to find a way of associating these
complex plane we points with the pixels in an array of colour values that
are interested in. We could be plotted using the imshow() function we used
“We want to colour each region also need to divide earlier. The complex plane region is just a list of points,
according to its convergence up this section into
regularly spaced
represented by complex numbers, and these don’t
have a colour associated with them to plot. We need
or divergence behaviour.” points, ultimately to give the imshow() plotting function something that
representing pixels in contains colour information. Also, imshow() expects
an image. to plot a two-dimensional array where the contents of
Python has a function linspace() which divides an a cell represent the colour to be plotted, not a long list
interval into evenly spaced points. Let’s imagine we of complex numbers like the ones we created earlier.
want a rectangle with bottom-left at (-2,-2) and the Given that the rows and columns of the plotted
top-right at (4,2). This has a horizontal length of 6, and array need to increment in whole units, we can simply
a vertical height of 4. Let’s divide the horizontal length place each of the evenly spaced points between the
into 12 sections, and the vertical into 8. The following bottom-left and top-right into the array. So if the points
After each iteration of the
‘multiply by 2’ function, Python code shows how you can use the familiar were 0.5 units apart on the complex plane, they would
the results get ever further Python loops over each element of linspace lists to be 1 unit apart in the array.
from each other – this is create the coordinates for each test point within this Let’s now define the complex plane region. Enter
divergence. rectangle. and run the following code. It makes sense to place
this at the top of your IPython notebook because it
iterate function “multiply by 2”, start value 2 sets out up front which region you are interested in.
Use the button marked as ‘Insert Cell Above’ to create
2400
a new cell at the top.
# set the location and size of the complex plane rectangle
1800
xvalues = linspace(-2.25, 0.75, 1000)
yvalues = linspace(-1.5, 1.5, 1000)
xlen = len(xvalues)
ylen = len(yvalues)
600 The first instruction creates a list of 1000 points
evenly placed between -2.25 and 0.75, inclusive.
These will be the horizontal divisions of the rectangle,
0 and we’ll call the list xvalues. Similarly, yvalues is the
0 2 4 6 8
list of 1000 evenly spaced points between -1.5 and
iteration
1.5. The last two lines simply take the length of the
lists and assign them to variables.
102 www.linuxvoice.com
MANDELBROT & PYTHON CODING
value
returned values from the mandel() function.
for ix in xrange(xlen):
for iy in xrange(ylen):
2.5
cx = xvalues[ix]
cy = yvalues[iy] 0
0 2 4 6 8
c = complex(cx, cy)
iteration
atlas[ix,iy] = mandel(c,40)
www.linuxvoice.com 103