Saturday, November 13, 2010

Using Python To Draw The Mandelbrot Set

I recently watched a documentary on the discovery of the Mandelbrot Set on youtube and it sparked my curiosity. I went ahead and made a little python app that draws the famous Mandelbrot set in a wxpython window. You can see the result of my work and the source code below. It is by no means useful or elegant code but it was a fun exercise!

import wx

class MandelbrotFrame(wx.Frame):
 def __init__(self, parent):
  wx.Frame.__init__(self, parent, id=wx.ID_ANY, title='Mandelbrot!', style=wx.DEFAULT_FRAME_STYLE & ~wx.RESIZE_BORDER)
  self.DrawingPanel = DrawingPanel(self)
  sizer = wx.BoxSizer(wx.VERTICAL)
  sizer.Add(self.DrawingPanel, 1, wx.EXPAND|wx.ALL, 5)
class DrawingPanel(wx.Panel):
 def __init__(self, parent):
  wx.Panel.__init__(self, parent, id=wx.ID_ANY, size=(600,500), style=wx.SIMPLE_BORDER)
  self.Bind(wx.EVT_PAINT, self.OnPaint)
  self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
 def OnEraseBackground(self, event):
 def OnPaint(self, event):
  dc = wx.BufferedPaintDC(self)
 def Draw(self, dc):
  for x in range(0, 600):
   real = -2 + x * ((1 - -2.0) / 600.0) 
   for y in range(0, 500):
    img = 1.2 - y * ((1.2 - -1.2) / 500.0)
    c = complex(real, img)
    z = 0
    for i in range(0, 30):
     z = z**2 + c
     if abs(z) > 2:
    if abs(z) >= 2:
     dc.SetPen(wx.Pen(wx.Colour(0, 8.5*i, 8.5*i)))
     dc.DrawPoint(x, y)
     dc.SetPen(wx.Pen(wx.Colour(0, 5, 5)))
     dc.DrawPoint(x, y)

if __name__ == '__main__':
 print 'Mandelbrot starting...'
 app = wx.App(0)
 frame = MandelbrotFrame(None)

1 comment:

  1. Master Framing are the experts in framing in Sydney.
    We specialize in memorabilia framing, custom picture framing, canvas stretching and photo mounting.
    We have grown into one of the most competitive picture framers in New South Wales,
    offering a large range of picture frames and picture framing services.

    perspex frames