#!/usr/bin/env python # -*- coding: utf-8 -*- from pylab import * from PIL import Image from math import sqrt, log import itertools maxinter = 50 d = 2 def main_ascii(): r=range print"\n".join("".join("# "[abs(reduce(lambda z,_:z*z+x/48.+y/24j,r(99)))<=2]for x in r(-96,97))for y in r(-48,49)) def mandel(x, y): """ Mandelbrot implementation in pure Python. """ x0, y0 = x, y x, y = 0, 0 # print "[Mandelbrot] Input is z =", complex(x, y) for n in xrange(maxinter+1): if x**2 + y**2 > 4: # print "[Mandelbrot] Success for z = {z}: n = {n}.".format(z=complex(x, y), n=n-1) break xnew, ynew = (x**2 - y**2 + x0), (2*x*y + y0) if (x, y) == (xnew, ynew): break x, y = xnew, ynew # https://en.wikipedia.org/wiki/Mandelbrot_set#Continuous_.28smooth.29_coloring if n < maxinter: zn = sqrt(x**2 + y**2) try: nu = log(log(zn, 2), 2) n -= nu except: pass # print "[Mandelbrot] Failed for z =", complex(x, y) return n N_default = 300 def main_pylab(N = N_default): """ Draw a basic Mandelbrot set, with colors, with MatPlotLib. """ print "Launching Mandelbrot plotting for {N} complex points in [-2.5, 1] × [-1, 1].".format(N=N**2) # Points x, y allx = linspace(-2.5, 1, N) ally = linspace(-1, 1, N) X, Y = meshgrid(allx, ally) # Performance is OK ? Z = map(lambda y: map(lambda x: mandel(x, y), allx), ally) fig = figure() axis("equal") xlabel("x Axis") ylabel("y Axis") title(u"Mandelbrot set for {N} complex points in [-2.5, 1] × [-1, 1].".format(N=N**2)) contourf(X, Y, Z, 80, alpha=1.0, cmap="gray") # Save the figure name_figure = "Mandelbrot__N_{N}".format(N=N) savefig("{}.png".format(name_figure)) print "[INFO] Figure saved to {}.png !".format(name_figure) savefig("{}.svg".format(name_figure)) print "[INFO] Figure saved to {}.svg !".format(name_figure) show() return name_figure # FIXME do it def main(N = N_default): """ Draw a basic Mandelbrot set, in gray-scale, with PIL.Image. """ print "Launching Mandelbrot plotting for {N} complex points in [-2.5, 1] × [-1, 1].".format(N=N**2) im = Image.new("RGB", (N, N)) # Points x, y allx = linspace(-2.5, 1, N) ally = linspace(-1, 1, N) for i, x in enumerate(allx): for j, y in enumerate(ally): n = mandel(x, y) if n == maxinter: color_value = 255 else: color_value = n*10 % 255 im.putpixel((i, j), (color_value, color_value, color_value)) im.save("mandelbrot.png", "PNG") print "The picture has been saved to mandelbrot.png" return "mandelbrot" if __name__ == "__main__": main()