Skip to content

Instantly share code, notes, and snippets.

@kantale
Created January 30, 2013 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kantale/4673642 to your computer and use it in GitHub Desktop.
Save kantale/4673642 to your computer and use it in GitHub Desktop.
Mandelbrot fractal
"""
This script uses the cplot function in mpmath to plot the Mandelbrot set.
By default, the fp context is used for speed. The mp context could be used
to improve accuracy at extremely high zoom levels.
"""
import mpmath
import cmath
import StringIO
import urllib, base64
import matplotlib.pyplot as plot
def Mandelbrot(ITERATIONS = 50, POINTS = 90000, ESCAPE_RADIUS = 8,
RE = [-2.5, 1.5], IM = [-1.5, 1.5]):
ctx = mpmath.fp
# A pretty subplot
#RE = [-0.96, -0.80]
#IM = [-0.35, -0.2]
def mandelbrot(z):
c = z
for i in xrange(ITERATIONS):
zprev = z
z = z*z + c
if abs(z) > ESCAPE_RADIUS:
return ctx.exp(1j*(i + 1 - ctx.log(ctx.log(abs(z)))/ctx.log(2)))
return 0
imgdata = StringIO.StringIO()
ctx.cplot(mandelbrot, RE, IM, points=POINTS, file=imgdata)
imgdata.seek(0) # rewind the data
uri = 'data:image/png;base64,' + urllib.quote(base64.b64encode(imgdata.buf))
print '<img src = "%s"/>' % uri
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment