Skip to content Skip to sidebar Skip to footer

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 I am bit unsure how the fractal generations work. I believe we start w

Solution 1:

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

defdraw_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 / 3for i inrange(3):
            for j inrange(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

Post a Comment for "Generating A Fractal In Python"