# Pretty fractal

I was experimenting with a pseudo-many-worlds quantum physics idea, and this screenshot came of it:Beautiful, isn't it? Here's the source if you want to play around, it's optimized as much as I know how without switching to C, any suggestions would be welcome:

import pygame

from pygame.locals import *

from math import sin, cos, pi

pygame.init()

screen = pygame.display.set_mode((800,650), HWSURFACE|DOUBLEBUF)

clock = pygame.time.Clock()

base = pygame.Surface((10,10))

pygame.draw.circle(base, (255,255,255), (5,5), 5)

base.set_colorkey((0,0,0))

next_circs = [(395,320)]

keep_going = 1

poses = {}

angs = range(9)

off = 50

while keep_going:

clock.tick(1)

for event in pygame.event.get():

if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):

keep_going = 0

print len(next_circs)

next_circs_h = []

for c in next_circs:

poses[c] = 0

screen.blit(base, (c[0] - 5, c[1] - 5))

for i in angs:

topleft = c[0] + off*cos(i*pi/4), c[1] + off*sin(i*pi/4)

if not poses.has_key(topleft):

next_circs_h.append(topleft)

next_circs = next_circs_h

pygame.display.flip()

Note I also tried two memoization techniques but the raw sin and cos appear to be faster anyway:

# first attempt

class memoize:

def __init__(self, fn):

self.mems = {}

self.fn = fn

def __call__(self, x):

if self.mems.has_key(x):

return self.mems[x]

else:

y = self.fn(x)

self.mems[x] = y

return y

# second attempt, almost as fast as raw sin/cos,

# a few secs faster than above

def memoize(f):

cache = {}

return lambda *args: cache[args] if args in cache else cache.update({args: f(*args)}) or cache[args]

@memoize

def cos_mem(x):

return cos(x)

@memoize

def sin_mem(x):

return sin(x)

#### Posted on 2010-11-22 by Jach

**Permalink:** https://www.thejach.com/view/id/145

**Trackback URL:** https://www.thejach.com/view/2010/11/pretty_fractal

## Recent Posts

2023-05-192023-05-052023-04-042023-03-292023-03-06