This example illustrates the use of NumPy's boolean indexing facilities to generate an image of the Mandelbrot set.
1 from numpy import *
2 import pylab
3
4 def mandelbrot( h,w, maxit=20 ):
5 '''Returns an image of the Mandelbrot fractal of size (h,w).
6 '''
7 y,x = ogrid[ -1.4:1.4:h*1j, -2:0.8:w*1j ]
8 c = x+y*1j
9 z = c
10 divtime = maxit + zeros(z.shape, dtype=int)
11
12 for i in xrange(maxit):
13 z = z**2 + c
14 diverge = z*conj(z) > 2**2 # who is diverging
15 div_now = diverge & (divtime==maxit) # who is diverging now
16 divtime[div_now] = i # note when
17 z[diverge] = 2 # avoid diverging too much
18
19 return divtime
20
21 pylab.imshow(mandelbrot(400,400))
22 pylab.show()