def mandelbrot(c, max_iterations=100):
z = 0
n = 0
while abs(z) <= 2 and n < max_iterations:
z = z*z + c
n += 1
if n == max_iterations:
return 0
else:
return n
The mandelbrot function takes a complex number c and a maximum number of iterations max_iterations. It returns 0 if c is in the Mandelbrot set, and the number of iterations required to escape the set otherwise.
Define the range of the complex plane that you want to plot:
Here, we are defining a range of 1000 evenly spaced points between -2 and 1 on the real axis, and a range of 1000 evenly spaced points between -1 and 1 on the imaginary axis.
Use np.meshgrid to create a grid of complex numbers:
real_part, imag_part = np.meshgrid(real_range, imag_range)
c = real_part + 1j*imag_part
Calculate the Mandelbrot set for each point in the grid:
The extent argument sets the range of the axes, and imshow takes the transpose of the Mandelbrot set array (mandelbrot_set.T) to ensure that the axes are oriented correctly. The xlabel and ylabel functions set the labels for the axes, and show displays the plot.
Putting it all together, the complete code looks like this:
import numpy as np
import matplotlib.pyplot as plt
def mandelbrot(c, max_iterations=100):
z = 0
n = 0
while abs(z) <= 2 and n < max_iterations:
z = z*z + c
n += 1
if n == max_iterations:
return 0
else:
return n
real_range = np.linspace(-2, 1, 1000)
imag_range = np.linspace(-1, 1, 1000)
real_part, imag_part = np.meshgrid(real_range, imag_range)
c = real_part + 1j*imag_part
mandelbrot_set = np.vectorize(mandelbrot)(c)
plt.imshow(mandelbrot_set.T, extent=[-2, 1, -1, 1])
plt.xlabel('Real')
plt.ylabel('Imaginary')
plt.show()
When you run this code, you should see a plot of the Mandelbrot set.