[Edu-sig] a Mandelbrot Set in a few lines of Python
Kirby Urner
kurner at oreillyschool.com
Fri Jun 19 19:12:27 CEST 2015
I'm pleased how little code is required to make a decent Mandelbrot Set
image using Numpy + PIL, neither of which am I expert at using. This is
how one learns. :-D
Here's how it looks on my screen:
https://flic.kr/p/uR81qU
For more about using fractals in teaching:
Fractals, Graphics, and Mathematics Education,
edited by Michael Frame and Benoit B. Mandelbrot
(c) 2002, Mathematical Association of America
ISBN: 0-88385-169-5
====
'''
Produces a decently high rez b/w graphic of Mandelbrot Set in
under a minute using default parameters. Not super fast, but
conceptually useful both for the mathematics and for the demo
of numpy + PIL in an I-Python Notebook.
(cl) Kirby Urner, MIT License, 2015
Pilot study for O'Reilly School of Technology
Using I-Python Notebook + pillow (PIL fork) + in Anaconda distro
'''
from PIL import Image
import numpy as np
def setup(pixels=(3200,2400), offset=(-2.5, 1.2), inc=1/1000):
'''
Create patch of complex plane c for z = z**2 + c itereactions
pixels(columns, rows), offset(left, top), inc = step
'''
x, y = pixels
offx, offy = offset
field = np.zeros((x, y)).astype(np.complex)
for j in range(y):
for i in range(x):
field[i][j] = complex( offx + inc * i, offy - inc * j)
return field
def mandelbrot_set(c):
'''
Apply Mandelbrot transform (orbit of 0) to c
'''
z = np.zeros(c.shape).astype(np.complex) # starts 0s
for idx in range(100):
z = z * z + c
idx = abs(z) >= 2 # continue weeding out
z[idx] = 3+0j # stamp out-of-bounds with 3
newf = (abs(z) < 2).astype(np.ubyte) # keep those in set
newf = newf * 255 # turn them white
im = Image.fromarray(newf)
im = im.rotate(90)
return im
m = setup()
image = mandelbrot_set(m) # may take 30 seconds or more!
image.save('mandelbrot.png', "png")
image.show()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20150619/a10f48a8/attachment.html>
More information about the Edu-sig
mailing list