The user wants a Python script to generate fractal images.
I need to decide which fractal to generate. The Mandelbrot set is the classic choice, but the Julia set is also popular and visually interesting.
It's best to provide a script that can handle at least the Mandelbrot set, and perhaps make it configurable or include the Julia set logic too, or just stick to a really nice, well-commented Mandelbrot generator.
Key requirements for a "good" script:
- Libraries:
numpy for the math (arrays are faster than loops in Python) and matplotlib for saving/displaying the image.
- Math: The core logic involves iterating zn+1=zn2+c.
- Coloring: A simple black-and-white image is boring. A color map based on the number of iterations looks much better.
- Performance: Python loops are slow. Vectorization with
numpy is essential for a smooth experience.
- Output: The script should save the image to a file.
Drafting the code structure:
- Import numpy and matplotlib.pyplot.
- Define constants (image size, zoom level, center point, max iterations).
- Create a grid of complex numbers (x, y) representing the coordinates.
- Initialize the z array and the iteration count array.
- Vectorized loop:
- Identify points where ∣z∣<2 (divergence check).
- Update z=z.
Refining the choice of fractal:
The Mandelbrot set is the standard. I will implement that, but I'll structure the code so it's easy to modify.
Step-by-step implementation plan:
- Imports:
numpy, matplotlib.pyplot.
- Function
mandelbrot(c, max_iter): This might be too slow if done per element. Better to vectorize the whole process.
- Setup:
- Width/Height (pixels).
- x/y bounds (complex plane).
max_iter (resolution of detail).
- Coordinate generation:
- Use
np.linspace for x and y.
- Create a meshgrid.
- Combine into a complex array C.
- Iteration logic:
- Z=np.zeros_like( (or start with for Julia, but 0 for Mandelbrot).
Adding a "twist":
To make the answer better, I should include the Julia Set logic as well, since it's almost the same code. I can write a class or a switch, but separate functions are clearer for a script.
Let's write the specific Numpy vectorized logic:
x = np.linspace(-2.5, 1.0, width)
y = np.linspace(-1.5, 1.5, height)
X, Y = np.meshgrid(x, y)
C = X + 1j * Y # The grid of complex numbers
Z = np.zeros_like(C)
div_time = np.zeros(C.shape, dtype=int) # To store color values
for i in range(max_iter):
# We keep working on points that haven't diverged yet
mask = np.abs(Z) <= 2
Z[mask] = Z[mask]**2 + C[mask]
div_time[mask] = i
Self-correction: The logic div_time[mask] = i overwrites previous iteration counts. I want div_time to store the first time it diverged.
Actually, usually div_time stores the number of iterations reached before diverging.
Revised logic:
Initialize div_time to max_iter.
Inside loop:
Check divergence.
Update Z.
Record i where Z first became > 2.
Better yet, use a slightly optimized common snippet for visualization:
div_time starts as 0.
Loop i from 0 to max_iter:
Z = Z**2 + C
diverged = (np.abs(Z) > 2) & (div_time == 0)
div_time[diverged] = i
Z[np.abs(Z) > 2] = 0 (Prevent overflow, effectively stops calculating for this pixel)
Wait, strictly speaking for Mandelbrot:
z0=0
zn+1=
If , it diverges.
Let's stick to a clean, vectorized implementation.
Code structure:
generate_mandelbrot function.
generate_julia function (optional but nice).
save_image logic.
__main__ block to run it.
I will provide a single script that generates the Mandelbrot set by default, but I'll add comments on how to tweak it or generate a Julia set, as the math is very similar.
Coloring:
Standard colormaps (viridis, magma, hot) work well. I'll use 'magma' or 'inferno' for that deep-space look.
Prerequisites:
The user needs numpy and matplotlib. I should mention this.
Final Polish:
Add comments explaining the math.
Make the resolution decent (e.g., 1000x1000) but not too slow.
Add logic to save to a file.
Let's refine the Julia set part. If I include it, the script becomes 2x longer. Maybe just stick to Mandelbrot to be concise, but mention that changing C to a constant and starting Z at the grid coordinates makes it a Julia set. Actually, providing a function for both makes the script "complete".
Let's write the script.
Script outline:
import numpy as np
import matplotlib.pyplot as plt
def mandelbrot(width, height, max_iter):
# Setup coordinates
# Create C
# Iterate
# Return iteration grid
def plot_fractal(fractal_data, filename):
# Plot and save
Details on Numpy:
The trick Z[diverged] = 2 helps keep numbers small and prevents NaN warnings.
Actually, if Z becomes large, squaring it causes overflow. We should mask it.
Z[abs(Z) > 2] = 0 works, but then 0^2 + C is just C, so it oscillates.
Common practice: Just don't update them anymore.
Use a boolean mask active.
mask = (np.abs(Z) <= 2) & (div_time == max_iter)
Z[mask] = Z[mask]**2 + C[mask]
Let's write the prompt response now.
- Intro.
- Requirements (pip install).
- The Code (heavily commented).
- Explanation of how it works.
- How to customize (colors, zoom).
Here is a complete, high-performance Python script to generate the Mandelbrot Set.
I have used numpy for vectorization (which makes it much faster than standard Python loops) and matplotlib for generating the image file.
Prerequisites
You will need to install the necessary libraries if you haven't already:
pip install numpy matplotlib
The Python Script
Save this code as fractal_generator.py and run it. It will generate a file named mandelbrot.png.
import numpy as np
import matplotlib.pyplot as plt
def generate_mandelbrot(width, height, x_min, x_max, y_min, y_max, max_iter):
"""
Generates a Mandelbrot set fractal image.
Parameters:
- width, height: Image dimensions in pixels
- x_min, x_max, y_min, y_max: The complex plane boundaries
- max_iter: Maximum number of iterations to determine divergence
"""
# 1. Create the coordinate grids
# x ranges from x_min to x_max
x = np.linspace(x_min, x_max, width)
# y ranges from y_min to y_max
y = np.linspace(y_min, y_max, height)
# Create a meshgrid to represent the complex plane (c = x + iy)
X, Y = np.meshgrid(x, y)
C = X + 1j * Y
# 2. Initialize arrays
# Z represents the iterative sequence z = z^2 + c
Z = np.zeros(C.shape, dtype=complex)
# M stores the "escape time" (number of iterations before divergence)
# Initialize with max_iter (assuming points don't diverge initially)
M = np.full(C.shape, max_iter, dtype=int)
# 3. Vectorized Iteration
for i in range(max_iter):
# Identify pixels that haven't diverged yet (|z| <= 2)
mask = np.abs(Z) <= 2
# Update Z for active pixels: z = z^2 + c
Z[mask] = Z[mask] ** 2 + C[mask]
# Update the escape time for pixels that just crossed the threshold
# Logic: If |Z| > 2 and we haven't recorded an exit time yet
diverged_now = (np.abs(Z) > 2) & (M == max_iter)
M[diverged_now] = i
return M
def save_fractal(matrix, filename, colormap='hot'):
"""
Saves the fractal matrix as an image.
"""
plt.figure(figsize=(10, 10))
# Use 'extent' to map pixels back to complex coordinates if needed
# origin='lower' puts the imaginary axis increasing upwards
plt.imshow(matrix, cmap=colormap, origin='lower', extent=[-2.5, 1.0, -1.5, 1.5])
plt.colorbar(label='Iteration count')
plt.title("Mandelbrot Set")
plt.xlabel("Re(c)")
plt.ylabel("Im(c)")
plt.savefig(filename, dpi=300, bbox_inches='tight')
plt.close()
print(f"Fractal saved to {filename}")
if __name__ == "__main__":
# Image settings
WIDTH, HEIGHT = 1920, 1080 # Resolution
# Complex plane bounds (Standard Mandelbrot view)
X_MIN, X_MAX = -2.5, 1.0
Y_MIN, Y_MAX = -1.5, 1.5
# Calculation depth
MAX_ITERATIONS = 256
print("Generating fractal... (this may take a few seconds)")
# Generate the data
fractal_data = generate_mandelbrot(WIDTH, HEIGHT, X_MIN, X_MAX, Y_MIN, Y_MAX, MAX_ITERATIONS)
# Save the image
# Try different colormaps: 'magma', 'inferno', 'plasma', 'viridis', 'binary'
save_fractal(fractal_data, "mandelbrot.png", colormap='magma')
How it works
- The Math: The Mandelbrot set is defined by the equation Zn+1=Zn2+C. For every pixel on the screen, we treat its coordinates as a complex number . We iterate the equation to see if the magnitude of goes toward infinity (diverges).
How to customize it
1. Zooming In
To see the infinite detail of the fractal, change the X_MIN, X_MAX, Y_MIN, Y_MAX variables to focus on a small area.
Example: Zoom into the "Seahorse Valley":
X_MIN, X_MAX = -0.75, -0.74
Y_MIN, Y_MAX = 0.1, 0.11
2. Changing Colors
In the save_fractal function call, change the colormap parameter. Popular options include:
'magma' (Default in script)
'hot' (Classic look)
'twilight_shifted' (Psychedelic)
'binary' (Black and white)