_personalPrez

Prez Jordan - Blogger, House Enthusiast, Coder, and President.

http://twitter.com/ilictronix
http://ilictronix.com
http://facebook.com/jscales
~ Thursday, December 10 ~
Permalink

Mandelbrot Set in Python

The Mandelbrot Set is sexy as hell, there’s no getting past that. Learning about it for 15 minutes in my Algebra II class years ago was more confusing than anything for my fellow classmates, thanks to an atrocious teacher, but my curiosity was sparked. I had started coding about that time, mainly in QBasic (hehe), and it was not until I picked up Python that I really thought about drawing this thing.

My lack of understanding for OOP at the tender age of 14 really set me back when working with the Tk interface library, so the first few weeks were chock full of copypasta, but I got better. In this code, however, I did not create any classes or anything, just kinda used the preset Tk() methods and whatnot. But it works :)

So let’s take a look at this beautiful code…

from Tkinter import *

def mandel(c):
        z=0
        for h in range(0,20):
            z = z**2 + c
            if abs(z) > 2:
                break
        if abs(z) >= 2:
            return False
        else:
            return True

root = Tk()
w = Canvas(root, width=600,height=600)
w.pack()

for hx in range(0,600,75):
    w.create_line(0,hx,600,hx,fill="blue")

for hy in range(0,600,75):
    w.create_line(hy,0,hy,600,fill="blue")

print "Initializing..."

for x in range(0,600):
    real = x / 200.0 - 1.5
    for y in range(0,600):
        img = y / 200.0 - 1.5
        c = complex(real, img)
        if mandel(c):
            w.create_line(x,600-y,x+1,601-y,fill="black")
            w.pack()

print "Complete!"

root.mainloop()    

My main function “mandel()” may confuse some of you. The mandlebrot set basically works like this. You have a set of numbers: z1, z2, z3, and z4. When given a complex number, c, you square the previous “z” and add c to it. z1 starts as just c, while z2 = z1^2 + c. If z4 is less than z2 and z3 is less than z1, the number c is a part of the Mandlebrot Set. To make things even more secure, I calculate up to z20, and if any z is greater than 2, said number c is NOT part of the set. Confusing, maybe.

So I have a 600 by 600 grid. To calculate the mandlebrot set, I assign the y axis to the coefficients of i, and the x axis to the coefficients of the real part. So 4+2i maps to (4,2). Using a bit of math, I scaled this system to easy-to-use integers so I could draw on a 600 x 600 grid.

I then simply check if a number is part of the set, using my method mandel(), and if it is, I map the complex number on the graph. To do this, I draw a line from x,y to x+1,y+1, because the Tkinter canvas does not support single pixels to be drawn, I think (hehe).

It’s pretty cool code, and the end result is beautiful.

Mandlebrot Set

Enjoy.

/prez


7 notes
  1. prezjordan posted this