Faster Mandelbrot image generation using numpy in Python

# - Mandelbrot image generation using numpy
# Written by Ted Burke - last updated 2-11-2014

import numpy

# Define image size and region of the complex plane
w,h = 1280,1280
remin,remax = -2.0, 2.0
immin,immax = -2.0, 2.0

# Create numpy arrays for pixels and complex values
p = numpy.zeros((h, w), dtype=numpy.uint8)
z = numpy.zeros((h, w), dtype=complex)
c = numpy.linspace(remin,remax,w) * numpy.ones((h,w)) + \
    1j * numpy.linspace(immax,immin,h).reshape(h,1) * numpy.ones((h,w))

# Iterative pixel calculation
for n in range(255):
    z = z*z + c
    p = p + (abs(z) < 2.0)

# Output image to binary PGM file
f = open('fractal.pgm', 'wb')
f.write('P5\n{0} {1}\n255\n'.format(w, h))

I ran the program and converted the image to PNG format using ImageMagick as follows:

convert fractal.pgm fractal.png


This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s