To draw the Mandelbrot set fractal in Python, we can use the following code:
main.py844 chars31 lines
Explanation:
We start by importing numpy and matplotlib.pyplot. We will use numpy to create arrays of complex numbers and matplotlib to visualize the fractal.
We define a function mandelbrot_set
that takes in the limits of the x and y axes, the size of the grid, and the maximum number of iterations. It returns an array of integers that represents the image of the Mandelbrot set on the complex plane.
We create a meshgrid of complex numbers c
on the x and y axes using numpy's linspace
function.
We initialize z
as a copy of c
.
We create an empty image array.
We loop over the maximum number of iterations and compute the Mandelbrot set for each pixel by iteratively squaring z
and adding c
. We keep track of the pixels that have not diverged using a boolean mask.
We add the mask to the image array.
We set the divergent pixels to zero to avoid computing them in the next iteration.
We transpose the image array and return it.
We define the limits and size of the plot, and call the mandelbrot_set
function to compute the image.
We plot the image using imshow
and specify the colormap and the extent of the plot.
We label the x and y axes and show the plot.
This will generate a colorful image of the Mandelbrot set fractal.
gistlibby LogSnag