Generating Fractals

This code was written as part of an exercise given to my Honors Physics students. The goal of the exercise is to expose students to the mathematics of fractals and complex numbers but also introduce coding in Python by encouraging them to experiment and play with the code to create their own fractals.

 
 

Mandelbrot Set

The Mandelbrot Set is the set of complex numbers, C, such that the following equation does not diverge when iterated from z = 0:

zn+1= zn2 + c

To determine if the equation is diverging, we need to set up a test.

To do so, we will use a loop and check if the absolute value of z_n is larger than a cutoff.

We define a function to do this that accepts an input value for c and returns -1 if c is in the Mandelbrot Set and the iteration that diverged if not.

We then use complex numbers to assign colors to our pixles based on inclusion in the Mandelbrot set.

fractal.png
 

Sample Code

cutoff = 2.0
def iterate_series(c):
    z_n = complex(0,0)
    for n in range(0,100):
        z_n = z_n*z_n + c
        if abs(z_n) > cutoff:
        return n
    return -1

Julia Set

The Julia Set is very similar to the Mandelbrot Set (the later of which being a mapping of the former). Take a peek at the code to see how the Julia Set is created. The key is switching from plotting c to plotting zn.

julia.png