Mandelbrot Set with Python

Abdul Salam
Level Up Coding
Published in
3 min readMar 15, 2020

--

“A Mandelbrot set marks the set of points in the complex plane such that the corresponding Julia set is connected and not computable. The Mandelbrot set is the set obtained from the recurrence relation, Z_(n) = Z²_(n-1) + c, where, Z_(0) = c. where c is a complex number” — Wolfram Mathworld.

Mandelbrot Set

The colors in a Mandelbrot set represents the iterations at which that complex number diverges to infinity (we can use here some threshold instead of infinity). Generally, the black color is for numbers that converge to zero (here we can use some maximum iteration limit under which if the number is not greater than the threshold value we assume it is converging to zero) and that's all in a Mandelbrot set (not really).

Let’s Code

The above code is used to find if a complex number diverges under max_steps and if it does then when.

Line 4: Maps the image coordinate to the real-valued number in the range [-2,0.47] for x and in the range [-1.12,1.12] for y (with a margin of 0.01 on all sides), which will be used to make complex numbers. Because it is known that the set is bounded with “The left-most extent of the set ends with the spike at x = -2, and the right side extends out to approximately x = 0.47. The top and bottom are at approximately y = ± 1.12, respectively” — fractalus.

Line 5: Creates a Numpy array of shape N*N, to store the pixel values of Mandelbrot Set.

Line 6–8: We loop through all pixels coordinates, using two loops, and calculate the pixel value for that coordinate (it is really the iteration value).

Line 9–10: put the pixel value in the image. I used “img[y][x]=255-it” because more iterations mean heading toward brack color. (I don’t know why does the image gets rotated -90 degree, but I rotated it 90 degrees by using “img[y][x]=255-it” instead of using “img[x][y]=255-it”) and returned the image “img”.

And that’s it we have the script, Now let's make some images.

n=1000
img = plotter(n, thresh=4, max_steps=50)
plt.imshow(img, cmap="plasma")
plt.axis("off")
plt.show()

The above code creates an image.

For more pixels in image increase N, for more details increase max_steps and don’t change thresh value else you will be doing redundant work (why?).

Try changing the argument for color map (cmap) in plt.imshow method from here, to get different color effects.

References

The beauty of complex numbers by Zack Start.

Mandelbrot Set, Wolfram Alfa MathWorld.

A Statistical Investigation of the Area of the Mandelbrot Set, fractalus.

--

--