zucian
zucian

Reputation: 31

Generating a fractal in python

I am currently working on a problem which involves plotting a fractal that has the form in the picture below

enter image description here

I am bit unsure how the fractal generations work. I believe we start with a single square, and then going from generation n to n+1 we place a new square at each diagonal of any square. I don't quite understand why this doesn't result in a fractal that looks like a giant net, but perhaps I will understand it better if i manage to code some of it.

Is there some smart way to work with grids in python? Any help is greatly appreciated as I do not have a lot of experience in working with and plotting fractals

Upvotes: 3

Views: 1980

Answers (1)

JohanC
JohanC

Reputation: 80299

You can create the fractal recursively. To draw it inside a square, if the lowest level has been reached, just draw the square. If not, draw 5 fractals of 1/3rd of the size:

import matplotlib.pyplot as plt

def draw_fractal(ax, levels=4, x=0, y=0, size=1):
    if levels == 0:
        ax.add_patch(plt.Rectangle((x, y), size, size, color='navy'))
    else:
        size3 = size / 3
        for i in range(3):
            for j in range(3):
                if (i + j) % 2 == 0:
                    draw_fractal(ax, levels - 1, x + i * size3, y + j * size3, size3)

fig, ax = plt.subplots()
ax.set_aspect(1)
ax.axis('off')
draw_fractal(ax)
plt.show()

The left image is the above fractal. For the center image, the test is changed to if i == 1 or j == 1:. And the right image uses if i != 1 or j != 1::

fractal in corners and center

Upvotes: 2

Related Questions