Friday, November 22, 2013

Mandelbrat Generator in Python

Here's some code I wrote a while back. As the title suggests, it generates the mandelbrat set using some methods from the excellent NumPy library. I've included a few photos to give you an idea of its "capabilities".

# This code generates the Mandelbrot series fractal.
# Author: Cooper Bell


import math
import numpy
import matplotlib.pyplot as plt

xmin, xmax = -2, 1		# extent of x range
ymin, ymax = -1, 1		# extent of y range
max_iteration = 200		# max number of iteration for unbound series
delta = .001			# increment for points
inner = 512				# color inside bulb
mand = []				# points in the mandelbrot set

x0 = [i for i in numpy.arange(xmin, xmax, delta)]
y0 = [i for i in numpy.arange(ymin, ymax, delta)]

for y in y0:
	row = []
	for x in x0:
	
		z, c = 0, x + 1j*y		# iteration for determining set
		iteration = 0			# initialize iteration number
		
		p = math.sqrt((x - 0.25)**2 + y**2)
		
		if (x < p - 2*p**2 + 0.25):			  # checks if point is in the cardioid
			color = inner
			
		elif (x + 1)**2 + y**2 < float(1/16): # checks if point is in 2-period bulb
			color = inner
			
		else:
			while (numpy.abs(z) < 2) and (iteration < max_iteration):
		
				z = z*z + c
				iteration += 1
			
				if numpy.abs(z) >= 2:	# check if z is not set member
					color = (float(iteration)/max_iteration)*512
				else:
					color = inner
				
		row.append(color)
	mand.append(row)

plt.figure()
plt.imshow(numpy.array(mand), cmap='flag', extent=(xmin, xmax, ymin, ymax))
plt.axis('off')
plt.show()

No comments:

Post a Comment