[Edu-sig] Simple Fractal

kirby urner kirby.urner at gmail.com
Mon May 1 06:33:38 CEST 2006


Here's a simple Mandelbrot class I plan to use next week.  The output
is mindless in this case, but reminiscent of what Mandelbrot first
started seeing at IBM i.e. vague X-ray visions, nothing like the high
resolution colorful MRI photographs we get today.  In this case, the
output is just ascii characters.

Future subclasses will take the same information and convert it to
POV-Ray and/or VPython, with a color palette added (color is a
function of the rate of divergence).

Anyway, just studying this source code helps make the concept of
"Mandelbrot Set" become clear, once you've mastered basic Python.

>>> import quickfractal
>>> f = quickfractal.Mandelbrot((-3,-2),(2,2),0.05)
>>> f.checkc()

"""

quickfractal.py
range through complex plane, lower left to upper right,
generating corresponding ascii depending on whether
z = z*z + c converges or diverges.

"""

class Mandelbrot (object):

    def __init__(self, lowleft, upright, step,
                 filename="simpfract.txt",
                 filepath="c:/python24/Lib/site-packages/"):
        self.lowleft = lowleft
        self.upright = upright
        self.step = float(step)
        self.filename = filename
        self.filepath = filepath

    def checkc(self):
        output = file(self.filepath + self.filename, 'w')
        re = self.lowleft[0]
        while re <= self.upright[0]:
            im = self.lowleft[1]
            while im <= self.upright[1]:
                c = complex(re,im)
                z = 0j
                for k in range(7):
                    z = z**2 + c
                if abs(z)<10:
                    output.write('*')  # converges
                else:
                    output.write('.')  # diverges
                im += self.step
            re += self.step
            output.write('\n')
        output.close()


More information about the Edu-sig mailing list