Skip to content

Instantly share code, notes, and snippets.

@bytezen
Created August 8, 2012 06:11
Show Gist options
  • Save bytezen/3292705 to your computer and use it in GitHub Desktop.
Save bytezen/3292705 to your computer and use it in GitHub Desktop.
Mandlebrot implementation in Python with numpy, pygame
import pygame
from pygame import surfarray
from pygame.locals import *
import sys, numpy as n
# Based on code from D. Shiffman (http://processing.org/learning/topics/mandelbrot.html)
# and P. Bourke (http://paulbourke.net/fractals/mandelbrot/)
def main():
pygame.init()
size = width, height = 400,400
maxiterations = 200
xmin = -2.5
ymin = -2.
w = 4.
inf_threshold = 16
xmax = xmin + w
ymax = ymin + w
dx = float( (xmax-xmin) / width )
dy = float( (ymax-ymin) / height )
m = n.ones((width,height,3),dtype='int32')
y = ymin;
for i in range(height):
x = xmin;
for j in range(width):
z = n.complex(x,y)
c = z
for cnt in range(maxiterations):
z = z*z + c
if z.real*z.real + z.imag*z.imag > inf_threshold:
break
if cnt == maxiterations-1: #bounded
m[j][i] *= 0
else: #unbounded
norm = float(cnt)/inf_threshold
m[j][i] *= norm * 255 #(cnt * 16 % 255 )
x += dx
y += dy
screen = pygame.display.set_mode( m.shape[:2],0,32)
surfarray.blit_array(screen, m)
pygame.display.flip()
pygame.display.set_caption("mandlebrot")
while True:
for e in pygame.event.get():
if e.type == QUIT:
pygame.quit()
elif e.type == KEYDOWN:
if e.key == K_s:
pygame.image.save(screen,"mandelbrot03.png")
print "saving"
if __name__ == '__main__':
main()
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment