"""
Mandelbrot Fractal Generator
============================
This Python script generates a high-resolution image of the Mandelbrot set,
a famous fractal. It uses NumPy for efficient computation and Matplotlib
for visualization and saving the image.
Requirements:
- Python 3.x
- numpy
- matplotlib
Install with: pip install numpy matplotlib
Usage:
- Run the script: python mandelbrot.py
- It will generate 'mandelbrot.png' in the current directory.
- Customize parameters in the script (height, width, max_iter, etc.).
Features:
- Vectorized computation for speed.
- Adjustable resolution, iterations, zoom, and color map.
- Saves a high-DPI PNG image.
"""
import numpy as np
import matplotlib.pyplot as plt
def mandelbrot_set(h, w, max_iter=100, zoom=1.0, x_center=-0.5, y_center=0.0, escape_radius=2.0):
"""
Compute the Mandelbrot set iteration counts for a grid of points.
Args:
- h, w: height and width of the image in pixels.
- max_iter: maximum number of iterations per point.
- zoom: zoom factor (higher = closer view).
- x_center, y_center: center point of the view in complex plane.
- escape_radius: radius beyond which points escape to infinity.
Returns:
- 2D numpy array of iteration counts.
"""
# Scale the view window based on zoom
scale = 3.0 / zoom
x_min = x_center - scale / 2
x_max = x_center + scale / 2
y_min = y_center - scale / 2 * (h / w)
y_max = y_center + scale / 2 * (h / w)
# Create grid of complex numbers c
x = np.linspace(x_min, x_max, w)
y = np.linspace(y_min, y_max, h)
X, Y = np.meshgrid(x, y)
C = X + 1j * Y
# Initialize Z and divergence time
Z = np.zeros_like(C)
div_time = np.full(C.shape, max_iter, dtype=int)
# Iterate for each point
for i in range(max_iter):
mask = np.abs(Z) <= escape_radius
Z[mask] = Z[mask]**2 + C[mask]
newly_diverged = mask & (np.abs(Z) > escape_radius)
div_time[newly_diverged] = i
Z[~mask] = escape_radius # Cap escaped points
return div_time
def generate_fractal_image(filename='mandelbrot.png', height=1200, width=1800, max_iter=256):
"""
Generate and save the fractal image.
"""
# Compute the fractal
fractal = mandelbrot_set(
h=height,
w=width,
max_iter=max_iter,
zoom=1.0, # Increase for zoom (e.g., 300 for deep zoom)
x_center=-0.75, # Try -0.75, 0.1 for seahorse valley
y_center=0.1,
escape_radius=2.0
)
# Create figure with no axes
fig, ax = plt.subplots(figsize=(width/100, height/100), dpi=100)
ax.imshow(fractal, cmap='hot', extent=[0, 1, 1, 0], origin='lower')
ax.axis('off')
# Save high-quality image
plt.savefig(filename, dpi=300, bbox_inches='tight', pad_inches=0, facecolor='black')
plt.close()
print(f"Fractal image saved as '{filename}' ({width}x{height} pixels)")
if __name__ == "__main__":
generate_fractal_image('mandelbrot.png', height=1200, width=1800, max_iter=256)
How to Use:
Save the code as mandelbrot.py.
Run python mandelbrot.py.
A stunning mandelbrot.png will be created (high-res, ~1-2 MB).
Customization Examples:
Deep zoom into a bulb: Set zoom=400, x_center=-0.75, y_center=0.1.
Higher detail: Increase max_iter=512 (slower but sharper).
Different colors: Change cmap='hot' to 'viridis', 'plasma', 'twilight', etc.
Julia set variant: Modify the function to fix c and iterate over z grid.
This script is efficient (vectorized with NumPy) and produces publication-quality images. Enjoy exploring the infinite beauty of fractals! 🧩