Skip to content

Instantly share code, notes, and snippets.

@davechristian
Last active February 3, 2023 15:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davechristian/9427248 to your computer and use it in GitHub Desktop.
Save davechristian/9427248 to your computer and use it in GitHub Desktop.
Renders a pretty Mandelbrot set using Python. Created for PiCymru. Note that this script requires NumPy and PIL (Python Imaging Library). Tested using Python 3 on Raspbian OS, and Windows 10/11 (Anaconda).
# Python Mandelbrot set for PiCymru
# This version uses the Python Imaging Library AND NumPy
from PIL import Image
import numpy
WIDTH = 512
HEIGHT = 512
MAX_ITER = 25 # How many iterations to perform z=z2+c
pix = numpy.zeros((HEIGHT, WIDTH, 3), dtype=numpy.uint8)
# For each pixel in our little display...
for y in range(0, HEIGHT):
for x in range(0, WIDTH):
zoom = 0.3
# The z in the mandelbrot set is an imaginary number, made up of
# a real number and an imaginary component
real = (float(x) / float(WIDTH)) * (1.0 / zoom) + -2.1
imaginary = (float(y) / float(HEIGHT)) * (1.0 / zoom) + -1.6
# This is the constant, which is the 'c' element of the main equation (z=z2+c)
const_real = real
const_imaginary = imaginary
z2 = 0.0
for iteration in range(0, MAX_ITER):
temp_real = real
# Calculate z=z2+c
real = (temp_real * temp_real) - (imaginary * imaginary) + const_real
imaginary = 2.0 * temp_real * imaginary + const_imaginary
z2 = real * real + imaginary * imaginary
# If z2 exceeds 4.0 before we hit MAX_ITER then we exit the loop and the current pixel
# does not belong to the mandelbrot set
if z2 > 4.0:
break
# Plot the current pixel. If it's in the mandelbrot set then do nothing.
if z2 > 4.0:
c = iteration * 15 % 255
if c > 50:
pix.itemset((y,x,2), c)
else:
pix.itemset((y,x,2), 50)
mandelbrot = Image.fromarray(pix, 'RGB')
mandelbrot.save("mandelbrot.png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment