Certainly! Below is a high-quality Python program that displays the Mandelbrot set using matplotlib and numpy. It is optimized for clarity, performance, and visual quality. The program uses vectorized operations for speed and includes a smooth coloring technique for a beautiful gradient.
import numpy as np
import matplotlib.pyplot as plt
def mandelbrot(c, max_iter):
"""
Compute the Mandelbrot set escape times for each point in c.
Uses vectorized operations for performance.
"""
z = np.zeros(c.shape, dtype=np.complex128)
div_time = np.zeros(c.shape, dtype=int)
mask = np.ones(c.shape, dtype=bool)
for i in range(max_iter):
z[mask] = z[mask] * z[mask] + c[mask]
mask_new = np.abs(z) <= 2
div_now = mask & (~mask_new)
div_time[div_now] = i
mask = mask_new
if not mask.any():
break
div_time[div_time == 0] = max_iter
return div_time
def mandelbrot_smooth(c, max_iter):
"""
Compute a smooth coloring of the Mandelbrot set.
"""
z = np.zeros(c.shape, dtype=np.complex128)
div_time = np.zeros(c.shape, dtype=float)
mask = np.ones(c.shape, dtype=bool)
for i in range(max_iter):
z[mask] = z[mask] * z[mask] + c[mask]
mask_new = np.abs(z) <= 2
div_now = mask & (~mask_new)
# Smooth iteration count
div_time[div_now] = i + 1 - np.log(np.log2(np.abs(z[div_now])))
mask = mask_new
if not mask.any():
break
div_time[div_time == 0] = max_iter
return div_time
def plot_mandelbrot(xmin, xmax, ymin, ymax, width, height, max_iter):
# Create a grid of complex numbers
real = np.linspace(xmin, xmax, width)
imag = np.linspace(ymin, ymax, height)
c = real + imag[:, None] * 1j
# Compute the Mandelbrot set with smooth coloring
mandelbrot_set = mandelbrot_smooth(c, max_iter)
# Plotting
plt.figure(figsize=(10, 8))
plt.imshow(mandelbrot_set, extent=[xmin, xmax, ymin, ymax], cmap='twilight_shifted', origin='lower')
plt.colorbar(label='Escape time (smooth)')
plt.title("Mandelbrot Set")
plt.xlabel("Re")
plt.ylabel("Im")
plt.show()
if __name__ == "__main__":
# Parameters for the plot
xmin, xmax = -2.0, 1.0
ymin, ymax = -1.5, 1.5
width, height = 1000, 1000
max_iter = 500
plot_mandelbrot(xmin, xmax, ymin, ymax, width, height, max_iter)
Features:
- Smooth coloring: Uses a continuous escape time formula for smooth gradients.
- Vectorized computation: Uses NumPy arrays for fast computation.
- High resolution: 1000x1000 pixels by default.
- Nice colormap: Uses
twilight_shifted for a visually appealing color scheme.
- Adjustable parameters: Easily change zoom and resolution.
How to run:
- Make sure you have
numpy and matplotlib installed:
pip install numpy matplotlib
- Save the code to a file, e.g.,
mandelbrot.py.
- Run it:
python mandelbrot.py
You will see a beautiful Mandelbrot set rendered with smooth colors. You can zoom in by changing the xmin, xmax, ymin, and ymax parameters. Enjoy exploring!