The user wants Python code to calculate and visualize the Mandelbrot set.
1. Understanding the Request:
- Topic: Mandelbrot set.
- Task: Calculate and visualize (plot).
- Language: Python.
2. Mathematical Background:
- The Mandelbrot set is defined as the set of complex numbers c for which the function fc(z)=z2+c does not diverge to infinity when iterated from z=0.
- Iteration: zn+1=zn2+c, starting with .
- Escape condition: A heuristic is often used. If ∣zn∣>2, the sequence will escape to infinity. Therefore, points where ∣zn∣ stays after a large number of iterations are considered part of the set.
- Coloring:
- Points inside the set are usually colored black.
- Points outside the set are colored based on how quickly they escaped (the number of iterations it took for ∣z∣ to exceed 2).
3. Implementation Strategy:
- Grid Generation: Create a grid of complex numbers (c values) over a specific range (e.g., x: -2 to 1, y: -1.5 to 1.5).
- Calculation: Loop through each point in the grid. Iterate the function z=z2+c.
- Optimization (Crucial): Pure Python loops are very slow for image generation. I should use
numpy for vectorized operations to make it reasonably fast and responsive.
- Visualization: Use
matplotlib to display the 2D array as an image.
4. Drafting the Code (Mental or scratchpad):
- Import libraries:
numpy, matplotlib.pyplot.
- Define parameters:
width, height, max_iter, x_min, x_max, y_min, y_max.
- Create coordinate arrays:
np.linspace.
- Create complex grid:
C = X + Y * 1j (or use np.meshgrid).
- Vectorized logic:
- Initialize
Z array (zeros).
- Initialize
M array (to store iteration counts).
- Iterate
max_iter times.
- Inside loop:
Z = Z**2 + C.
- Check divergence:
diverged = np.abs(Z) > 2.
- Record iteration number where divergence occurred.
- Reset diverged points to 0 or handle them to avoid overflow errors (NaNs). Correction: In numpy, if I keep squaring infinity, it stays infinity, but it's computationally wasteful. Better to use a mask.
Refined Numpy Algorithm:
- Initialize
Z to zeros (same shape as C).
- Initialize
div_time to zeros (this tracks when it escaped).
- Initialize
mask (boolean array) to keep track of points that haven't diverged yet.
- Loop
i from 0 to max_iter:
Z[mask] = Z[mask]**2 + C[mask]
- Check divergence for the current active points:
newly_diverged = mask & (np.abs(Z) > 2)
- Update
div_time for newly_diverged to i.
- Update
mask to exclude newly_diverged.
5. Adding Features/Polish:
- Colormaps: The default is okay, but a continuous colormap (like 'magma', 'inferno', or 'twilight') looks much better than 'jet'.
- Resolution: Make the image size a variable.
- Interactivity (Optional): Zooming is cool, but standard code usually just outputs a static image. I will provide a high-quality static image generator and maybe mention zooming.
- Docstrings/Comments: Explain what the code does.
6. Writing the Code (Iterative refinement):
- Version 1 (Basic loops - too slow). Skip.
- Version 2 (Vectorized Numpy):
import numpy as np
import matplotlib.pyplot as plt
def mandelbrot_set(xmin, xmax, ymin, ymax, nx, ny, max_iter):
x = np.linspace(xmin, xmax, nx)
y = np.linspace(ymin, ymax, ny)
X, Y = np.meshgrid(x, y)
C = X + Y*1j
Z = np.zeros(C.shape, dtype=complex)
M = np.zeros(C.shape, dtype=int)
for i in range(max_iter):
mask = np.abs(Z) <= 2
Z[mask] = Z[mask]**2 + C[mask]
M[mask & (np.abs(Z) > 2)] = i
# Reset Z where |Z| > 2 to keep numbers manageable (avoid overflow)
# Actually, if we use M to track, we just don't update Z where it already diverged.
return M
Self-Correction on Version 2: The logic Z[mask]**2 works, but masking inside a loop can be slightly tricky with indices. A standard broadcasting approach is often cleaner:
Z = Z**2 + C
diverged = np.abs(Z) > 2
M[diverged] = i (Needs logic to prevent overwriting).
Better approach: Just iterate Z, and when the loop finishes, calculate the fraction of iterations required to escape. Or, simpler for a basic script:
Just compute Z. At the end, the points that didn't escape are part of the set. For coloring, we need the iteration count.
Let's stick to the mask approach for speed, preventing calculating on points that already "exploded".
7. Final Code Structure:
- Imports:
numpy, matplotlib.pyplot.
- Function
mandelbrot:
- Inputs: resolution, bounds, iterations.
- Logic: Vectorized iteration loop.
- Output: 2D array of iteration counts.
- Visualization:
plt.imshow.
plt.colorbar.
plt.show.
8. Visual Enhancements:
- Use
extent in imshow to map pixels to complex plane coordinates.
- Choose a nice colormap (e.g., 'plasma').
- Logarithmic scaling of the iteration counts can sometimes reveal more detail in the outer areas, but linear is fine for a standard start. Let's stick to standard linear interpolation of the colormap.
9. Code Review against constraints:
- Does it calculate? Yes.
- Does it visualize? Yes.
- Is it Python? Yes.
- Is it efficient? Yes, using Numpy.
10. Output Generation:
(Produces the Python code block with explanation). I will provide a version that is clean, commented, and runs efficiently using NumPy vectorization.
Self-Correction during coding: Be careful with overflow warnings in numpy if values get too huge. The condition |z| > 2 usually handles this, but strictly speaking, z can become massive. We should mask out points that have already diverged to avoid calculating infinity^2 or NaN errors.
Refined Loop Logic:
z = np.zeros(c.shape, dtype=complex)
div_time = np.zeros(c.shape, dtype=int)
diverged = np.zeros(c.shape, dtype=bool)
for i in range(max_iters):
z[~diverged] = z[~diverged]**2 + c[~diverged]
diverged = (np.abs(z) > 2)
div_time[diverged] = i
Actually, div_time should only be set once (the first time it diverges).
Correct logic:
for i in range(max_iters):
# Only update points that haven't diverged yet
mask = np.abs(z) <= 2
z[mask] = z[mask]**2 + c[mask]
# Record points that just crossed the threshold
# Note: this requires checking against the previous state or careful assignment.
# Standard trick: Initialize div_time to max_iters.
# If it diverges at step i, set it to i.
# If it's already not max_iters, leave it alone.
Let's write the solution now.
Here is efficient and clean Python code to calculate and visualize the Mandelbrot set.
This solution uses NumPy for vectorized calculations (which is much faster than standard Python loops) and Matplotlib for visualization.
Prerequisites
You will need to install the necessary libraries if you haven't already:
pip install numpy matplotlib
The Python Code
import numpy as np
import matplotlib.pyplot as plt
def mandelbrot_set(width, height, x_min, x_max, y_min, y_max, max_iter):
"""
Calculates the Mandelbrot set for a given grid and iteration limit.
Returns:
x_vals (np.array): x-coordinates
y_vals (np.array): y-coordinates
n (np.array): 2D array of iteration counts (the "image" data)
"""
# 1. Create the coordinate arrays
x_vals = np.linspace(x_min, x_max, width)
y_vals = np.linspace(y_min, y_max, height)
# 2. Create the meshgrid
# X and Y are 2D arrays representing the complex plane coordinates
X, Y = np.meshgrid(x_vals, y_vals)
# 3. Initialize arrays
# C: The complex constant for each pixel (c = x + iy)
C = X + 1j * Y
# Z: The iterating variable (starts at 0)
Z = np.zeros(C.shape, dtype=complex)
# N: The array storing the iteration count for each pixel
N = np.zeros(C.shape, dtype=int)
# 4. Vectorized Iteration
# We use a boolean mask to track which points haven't diverged yet
mask = np.ones(C.shape, dtype=bool)
for i in range(max_iter):
# Calculate Z = Z^2 + C only for points that haven't diverged
Z[mask] = Z[mask] * Z[mask] + C[mask]
# Check for divergence: |Z| > 2
diverged = np.abs(Z) > 2
# Update the iteration count for newly diverged points
# We store 'i' (the current iteration number)
N[mask & diverged] = i
# Update the mask to exclude diverged points from future calculations
mask[diverged] = False
# Optimization: Stop if all points have diverged
if not np.any(mask):
break
return x_vals, y_vals, N
# --- Configuration ---
# Resolution of the image (pixels)
WIDTH = 1000
HEIGHT = 1000
# Bounds of the complex plane (Standard view)
# Real axis: -2.5 to 1.0
# Imaginary axis: -1.0 to 1.0
X_MIN, X_MAX = -2.5, 1.0
Y_MIN, Y_MAX = -1.3, 1.3
# Maximum iterations (higher = more detail, but slower)
MAX_ITER = 256
# --- Execution ---
print("Calculating Mandelbrot Set...")
x, y, z = mandelbrot_set(WIDTH, HEIGHT, X_MIN, X_MAX, Y_MIN, Y_MAX, MAX_ITER)
print("Done.")
# --- Visualization ---
plt.figure(figsize=(10, 10))
# We use log scaling for better color gradient visibility
# extent sets the axis labels to the complex coordinates
plt.imshow(z, extent=[X_MIN, X_MAX, Y_MIN, Y_MAX], cmap='inferno', origin='lower')
plt.colorbar(label='Iteration count (Log Scale)')
plt.title('Mandelbrot Set')
plt.xlabel('Real Axis')
plt.ylabel('Imaginary Axis')
plt.tight_layout()
plt.show()
How it works:
- Grid Generation: We create a grid of complex numbers c using
np.meshgrid.
- Vectorization: Instead of looping through every single pixel (which is slow in Python), we use NumPy arrays to perform math on the entire grid at once.
- The Mask: We create a boolean mask (
True/False array). Once a point diverges (its magnitude exceeds 2), we mark it as False in the mask. This prevents the computer from wasting time doing math on points that have already "escaped."
- Colormap: We use the
inferno colormap, which is perceptually uniform and looks pleasing for mathematical sets, but you can swap 'inferno' with 'magma', 'viridis', 'jet', or 'binary'.
Zooming In
To zoom into a specific area (like the famous "Seahorse Valley"), simply change the X_MIN, X_MAX, Y_MIN, and Y_MAX variables in the configuration section. You will also likely need to increase MAX_ITER to see fine detail at deep zoom levels.
Example Zoom Coordinates (Seahorse Valley):
X_MIN, X_MAX = -0.8, -0.7
Y_MIN, Y_MAX = 0.0, 0.1
MAX_ITER = 500