March 2, 2010

Fractal & Python: Part II

After the Lorenz attractor, here is a little code for exploring the Mandelbrot Set. Of course, you could compute the same thing in CUDA with a 1000X speedup… but  it wouldn’t be pythonish as this !

from numpy import *
import matplotlib.pylab as pl
 
maxIteration = 128
z_min = -2-1j
z_max = 1+1j
 
# Set the image size here
imageSize = [512,512]
image = zeros(imageSize,int)
xValue = linspace(z_min.real, z_max.real, imageSize[0])
yValue = linspace(z_min.imag, z_max.imag, imageSize[1])
 
for i in arange(imageSize[0]):
	for k in arange(imageSize[1]):
		iteration = 0
		x = xValue[i]
		y = yValue[k]
		while (x*x+y*y < (2*2)) & (iteration < maxIteration):
			xtemp = x*x - y*y + xValue[i]
 			y = 2*x*y + yValue[k]
			x = xtemp
			iteration = iteration + 1
		if iteration == maxIteration:
			image[i,k] = 0
		else:
			image[i,k] = 255-iteration
 
pl.imshow(image)
pl.prism()
pl.show()

Leave a Reply