# Programming Fractals in Python

## Learn how to create beautiful fractals through Python.

# Fractals: A Brief Overview

What is the shape of a fern? What about a river or even a mountain? We cannot define them as just a square or cylinder using simple Euclidean Geometry. That’s why we have Fractal Geometry: the geometry of beautiful structures. Fractals can be seen everywhere in nature, and are formed by the repetition of steps over and over again.

Fractals can be hard to truly define, and are linked by these common features: zoom symmetry, complexity from simplicity and fractional dimensions. Another interesting fact is that most fractals are not a one dimensional or two dimensional shape but actually are in-between.

Anyways, enough information, let’s get into the three fractals we will be coding: the Koch Snowflake, Barnsley Fern and Mandelbrot Set!

# The Koch Snowflake

The Koch Snowflake, also known as the Koch island, is based on the Koch curve created in 1904 by Helge von Koch, a Swedish mathematician.

The snowflake is constructed by repeating a sequence of stages iteratively, starting off with an equilateral triangle, then:

- dividing the line segment into 3 with equal lengths
- drawing an equilateral triangle on the middle segment, pointing upwards
- removing the middle line segment (the base of the triangle)

For this fractal, we will be using a Python library called ‘Turtle’ to draw it, and will need to import it:

**import** turtle

Now, let’s start the creation of the Koch Snowflake by creating a function for the Koch curve. We will be using recursion, which is when a function calls itself directly or indirectly. The parameters of the function are:

**turtle**, which is going to be the turtle that will draw the fractal**divis**, which is how many times we are going to ‘do’ the steps mentioned above**size**, which defines how long each side of the equilateral triangle will be

Then, inside this function we have the base-case, signaling that when the number of divisions has reached 0, we will move the turtle forward the length of a side. However, if the divisions is greater than 1, we will have a for loop which uses the Lindenmayer system to draw the fractal.

The Lindenmayer system is a way to represent a recursive fractal in the form of a string. With the Koch snowflake, the initial string being “F-F-F” and the string rewriting rule, “F” → “F+F-F+F” and an angle of 60°. “F” means move forward, “+” means turn right by the angle, and “-” means turn left by the angle. With this, we get the following function:

**def **koch_fract(turtle, divis, size):

**if**(divis == 0):

turtle.forward(size)

**else**:

**for **angle **in **[60, -120, 60, 0]:

koch_fract(turtle, divis - 1, size / 3)

turtle.left(angle)

After creating the function, we can set some variables for the parameters to enter into the function:

`divis = 10 # any number of divisions, the larger the number, the more detailed the diagram`

size = 2000 # any length

Then, we must set up the turtle and screen to draw the fractal:

`wn = turtle.Screen()`

wn.setup(width=1000, height=500)

turtle.speed(100)

turtle.pendown()

Afterwards, we will use a for loop to use our Koch curve function to create the Koch Snowflake. We will call this Koch Curve function 3 times, each time turning the turtle 120° counterclockwise.

`for i in range(0, 3):`

koch_fract(turtle, divis, size)

turtle.left(-120)

Here is what it should look like:

# The Barnsley Fern

Let’s move on to the Barnsley Fern! It is a fractal first coined by British Mathematician, Michael Barnsley, in his book “Fractals Everywhere”. It is known as an “iterated function system” (IFS) fractal. The construction of this fractal makes use of Matrices, to learn more about Matrices, I would recommend this site.

The Barnsley Fern is created using this Matrix transformation:

Four different transformations are used, illustrated in the table below. Variables** a to f** are the coefficients, and **p **is the probability factor.

From this table, we can create the 4 functions for our program:

Now that we have a basic understanding of how the Barnsley Fern is generated, we can get started coding it!

First, import the following libraries:

**import **matplotlib.pyplot **as **plt

**from** random **import **randint

Since we will be plotting the fern on a scatter plot, we will need to create a list for the x and y arrays

`x = [0]`

y = [0]

Onto creating the fractal! We will use a **for loop** to iterate **n **times, the more times the program runs, the more elaborate the fractal. To create the probability factor, we will use the **randint **function from the **random **Python library to randomly select an integer between 1 and 100. Based on the probability factor, **p**, we will perform the aforementioned functions and add the result to the **x** and **y** lists.

`for i in range(0, 50000): `

p = randint(1, 100)

if p == 1:

x.append(0)

y.append(0.16*(y[i]))

if p >= 2 and p <= 86:

x.append(0.85*(x[i]) + 0.04*(y[i]))

y.append(-0.04*(x[i]) + 0.85*(y[i])+1.6)

if p >= 87 and p <= 93:

x.append(0.2*(x[i]) - 0.26*(y[i]))

y.append(0.23*(x[i]) + 0.22*(y[i])+1.6)

if p >= 94 and p <= 100:

x.append(-0.15*(x[i]) + 0.28*(y[i]))

y.append(0.26*(x[i]) + 0.24*(y[i])+0.44)

Once we have all the points, we can plot it using plt.scatter. The parameter **c** is the color of the points on the graph, which I set to a green using hexadecimal. If you want to hide the axes, use the function plt.axis(“off”)!

`plt.scatter(x, y, s = 0.2, c ='#5dbb63') `

plt.axis("off")

plt.show()

That’s how you create the Barnsley fern!

# The Mandelbrot Set

Last is the Mandelbrot Set, which is, in my opinion, one of the most beautiful fractals ever! The Mandelbrot Set is the set of complex numbers where the function does not diverge when iterated. You can find out more about the math behind the Mandelbrot Set from this website. In order to be programming this, we will be using iteration!

Like with the Barnsley Fern, we will be plotting the Mandelbrot set on a graph using matplotlib and numpy! Therefore, we will need to import these libraries:

**import** numpy **as** np

**import** matplotlib.pyplot **as** plt

Then, we will need to decide how many rows and columns we will need, this decides how detailed the set is, as well as the number of iterations we will use.

Afterwards, we will need to program two different functions:

- the first function will calculate a specific number in the Mandelbrot set
- the second function will calculate the numbers in the Mandelbrot set

Here is the first function:

`def mandelbrot(c, z):`

global iterations

count = 0

for a in range(iterations):

z = z**2 + c

count += 1

if(abs(z) > 4):

break

return count

The parameters c and z represent the points in the complex plane and coordinates respectively.

The second function is:

`def mandelbrot_set(x, y):`

m = np.zeros((len(x), len(y)))

for i in range(len(x)):

for j in range(len(y)):

c = complex(x[i], y[j])

z = complex(0, 0)

count = mandelbrot(c, z)

m[i, j] = count

return m

The parameters **x** and **y** are the **numpy** arrays of the x and y coordinates. We will first create an array with the shape of the x and y coordinates called **m**, and will be the complex plane coordinates. Then, we will iterate through the **x** array and **y** array using for loops. We will create the complex number of the **x** and **y** values and call our **mandelbrot(c, z) **function from before. Then, the count will be added to the **m** array. Afterwards, we will return the **m** array.

Now, we will need to create our Mandelbrot set from these functions and plot it using matplotlib!

# creating our x and y arrays

x = np.linspace(-2, 1, rows)

y = np.linspace(-1, 1, cols)# create our mandelbrot set

m = mandelbrot_set(x, y)# plot the set (best colors: binary, hot, bone, magma)

plt.imshow(m.T, cmap = "magma")

plt.axis("off")

plt.show()

Here is what it should look like! Isn’t it beautiful?

That’s how you can code the Koch Snowflake, Barnsley Fern and Mandelbrot Set! I hope you learned a lot and enjoyed coding them. Feel free to download my code from my GitHub.

Koch Snowflake: https://github.com/itsliterallymonique/Koch-Fractal-o_O

Barnsley Fern: https://github.com/itsliterallymonique/Barnsley-Fern

Mandelbrot Set: https://github.com/itsliterallymonique/Mandelbrot-Set