[Edu-sig] Another fractal

Kirby Urner urnerk@qwest.net
Sun, 02 Mar 2003 22:01:37 -0800


The code below produces a decent graphic of the Mandelbrot Set, when
run through Povray, the free ray tracer (Windows, Linux and more).
It's not at all fast, but then the code is straightforward, meaning
it's accessible to someone fairly new to Python.  No modules are
imported.  It's all built-in stuff.

Mixing Python and Povray is an old favorite around here.  This is
good for still pictures.  For dynamic stuff, OpenGL is more the way
to go (ala VPython), or perhaps PyGame.

Faster fractal calcs would involve using the Numeric package, or at
least a numeric array (from the array module) vs. a huge generic list
as below.  Or, better, since the results get saved in Povray, there's
no need for a persistent complex plane of any kind -- just a loop in
a loop would do the job (very standard procedural stuff).

Kirby

Here's the result:
http://www.inetarena.com/~pdx4d/ocn/python/mandelbrot.png
(cropped)

See also:  http://www.inetarena.com/~pdx4d/ocn/fractal.html
(different code, requiring additional modules)

====================

def mandelbrot():
     outfile = open("test2.pov",'w')
     header(outfile)

     # create complex plane
     cplane = [(x/200.0,y/200.0) for x in range(-400,401)
                                 for y in range(-400,401)]

     for x,y in cplane:
         c = complex(x,y)
         z = 0
         i = 0
         done = False
         while not done:
             i += 1
             z = z*z + c

             if i > 999:
                 # convergent -- color black
                 done = True
                 sphcolor = "rgb <%s, %s, %s>" % (0,0,0)

             elif abs(z)>1e6:
                 # divergent, compute color from iterations so far
                 done = True
                 r,g,b = str(i).zfill(3)
                 sphcolor = "rgb <0.%s, 0.%s, 0.%s>" % (r,g,b)

             if done:
                 # write the colored sphere, move on to the next one
                 povline = """sphere{<%s, %s, %s>, 0.01 texture{pigment 
{color %s} } no_shadow}\n""" \
                           % (x,y,0,sphcolor)
                 outfile.write(povline)

     outfile.close()

def header(wfile):
     """
     Standard Povray file header with some custom settings
     """
     wfile.write("""
//POV-Ray script
//version 3.1
global_settings { assumed_gamma 2.2 }
#include "colors.inc"

#declare Cam_factor =8;
#declare Camera_X = -1.0;
#declare Camera_Y = 0;
#declare Camera_Z = 1 * Cam_factor;

camera { location  <Camera_X, Camera_Y, Camera_Z>
          up        <0, 1.0,  0>    right     <-4/3, 0,  0>
          direction <-1, 0,  3>      look_at   <-1, 0, 0>
          rotate <0,0,0>}

light_source { <Camera_X - 2, Camera_Y + 5 , Camera_Z + 5> color White }
light_source { <Camera_X - 2, Camera_Y + 5 , Camera_Z - 3> color White }
light_source { <Camera_X + 2, Camera_Y - 5 , Camera_Z + 3> color White }
     """)