The user wants Python code to visualize fractals using recursive algorithms. This is a great opportunity to create comprehensive code that demonstrates various types of fractals. I'll create a well-documented script that shows different fractal types:
Mandelbrot Set - The classic complex number fractal
Let me create comprehensive, well-documented code with multiple fractal examples.
python
"""
Fractal Visualization using Recursive Algorithms
================================================
This module provides implementations of various recursive fractals:
1. Sierpinski Triangle
2. Koch Snowflake
3. Fractal Tree
4. Dragon Curve
5. Mandelbrot Set
6. Julia Set
7. Barnsley Fern
Author: Assistant
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.collections import LineCollection
import colorsys
from typing import List, Tuple, Optional
import warnings
warnings.filterwarnings('ignore')
# ============================================================
# 1. SIERPINSKI TRIANGLE
# ============================================================
def sierpinski_triangle(vertices: List[Tuple[float, float]],
depth: int,
ax: plt.Axes) -> None:
"""
Recursively draw a Sierpinski Triangle.
The Sierpinski Triangle is created by:
1. Start with an equilateral triangle
2. Subdivide it into 4 smaller triangles
3. Remove the center triangle
4. Repeat for the remaining 3 triangles
Args:
vertices: List of 3 (x, y) tuples defining triangle corners
depth: Current recursion depth (stops at 0)
ax: Matplotlib axes to draw on
"""
if depth == 0:
# Base case: draw the triangle
triangle = plt.Polygon(vertices, fill=True,
facecolor=plt.cm.viridis(np.random.random()),
edgecolor='black', linewidth=0.5)
ax.add_patch(triangle)
else:
# Compute midpoints of each side to create new triangles
midpoints = [
((vertices[0][0] + vertices[1][0]) / 2, (vertices[0][1] + vertices[1][1]) / 2),
((vertices[1][0] + vertices[2][0]) / 2, (vertices[1][1] + vertices[2][1]) / 2),
((vertices[2][0] + vertices[0][0]) / 2, (vertices[2][1] + vertices[0][1]) / 2)
]
# Generate three smaller triangles through recursive calls
sierpinski_triangle([vertices[0], midpoints[0], midpoints[2]], depth - 1, ax)
sierpinski_triangle([midpoints[0], vertices[1], midpoints[1]], depth - 1, ax)
sierpinski_triangle([midpoints[2], midpoints[1], vertices[2]], depth - 1, ax)
def plot_sierpinski(depth: int = 6) -> None:
"""Visualize Sierpinski Triangle fractal."""
fig, ax = plt.subplots(figsize=(10,
I'll complete the partial thought by copying over the next thinking up to the newline:
9))
# Define initial equilateral triangle vertices
height = np.sqrt(3) / 2
vertices = [(0, 0), (1, 0), (0.5, height)]
sierpinski_triangle(vertices, depth, ax)
ax.set_xlim(-0.1, 1.1)
ax.set_ylim(-0.1, 1.0)
ax.set_aspect('equal')
ax.set_title(f'Sierpinski Triangle (Depth: {depth})', fontsize=14)
ax.axis('off')
plt.tight_layout()
plt.show()
Now I'll summarize the key points:
I'm creating a Sierpinski Triangle visualization using recursive subdivision. The initial triangle is defined with precise geometric calculations, and the plot is configured to display the fractal clearly with equal aspect ratio and no axis. I'll calculate the peak point by rotating the line segment 60 degrees, creating an equilateral triangle's apex. Then I'll recursively generate Koch curve segments for each new line, breaking the original segment into smaller, intricate parts that build the fractal's characteristic geometric complexity.
The curve construction involves extending segments between points, systematically replacing each line with four smaller lines that create the distinctive Koch snowflake pattern. By recursively applying this transformation at each depth level, I'll generate increasingly detailed geometric structures.
I'll plot the snowflake by first establishing an initial equilateral triangle, then systematically transforming each side using the Koch curve algorithm to create the intricate, self-similar fractal design.
For each triangle side, I'll compute the curve points, carefully managing coordinate extraction and preparing a color gradient to visualize the fractal's progressive complexity. The gradient will map segment progression, highlighting the mathematical elegance of the snowflake's construction.
I'll complete the visualization by filling the snowflake with a soft cyan, ensuring equal aspect ratio and removing axis markings to emphasize the geometric purity. The title will succinctly capture the fractal's depth, presenting the mathematical intricacy.
The fractal tree function appears to be a recursive geometric drawing method, designed to generate branching structures through controlled angle and length transformations.
At each recursive step, the algorithm splits branches at precise angles, systematically reducing branch length. This creates a naturalistic, self-similar pattern mimicking tree growth, with parameters controlling the branching behavior and visual complexity.
The function takes precise geometric inputs - starting coordinates, current angle, branch length, and recursion depth - allowing flexible tree generation. By specifying branch angle and length reduction ratio, users can craft diverse tree-like fractals with mathematical precision.
The implementation will likely use trigonometric calculations to determine branch endpoints, with depth and length serving as termination conditions for the recursive process. plt.subplots(figsize=(12, 10))
ax.set_facecolor('#87CEEB') # Sky blue background
# Draw ground
ax.axhspan(-50, 0, color='#228B22', alpha=0.7)
# Start tree from bottom center, pointing up (90 degrees)
fractal_tree(0, 0, 90, 100, depth, ax, branch_angle)
ax.set_xlim(-200, 200)
ax.set_ylim(-20, 250)
ax.set_aspect('equal')
ax.set_title(f'Fractal Tree (Depth: {depth}, Branch Angle: {branch_angle}°)',
fontsize=14)
ax.axis('off')
I'll create a visualization with a sky blue backdrop and a green ground. Positioning the tree at the center bottom, I'll generate a fractal tree using the specified depth and branch angle. The plot will be symmetrically scaled and have a descriptive title, with axes hidden to focus on the tree's intricate structure. I'll plot the dragon curve by generating its L-system instructions and tracking the turtle's movement through coordinate transformations. Using trigonometric functions, I'll calculate each point's position based on the current angle and movement rules. The resulting curve will be visualized with a color gradient to highlight its intricate geometric progression.
I'll extract x and y coordinates from the points, then create line segments connecting each sequential point. By mapping these segments to a color spectrum using HSV colormap, I'll generate a visually dynamic representation of the fractal's complexity. The plot will automatically scale to fit the curve and maintain an equal aspect ratio for precise geometric rendering.
I'll complete the title formatting and remove axis labels to emphasize the curve's intricate geometry. The visualization will highlight the dragon curve's depth through a carefully constructed line collection.
The next mathematical exploration involves the Mandelbrot set, a fascinating complex plane visualization that examines the behavior of iterative sequences. I'll define a function to compute iteration counts for determining whether a point belongs to this iconic mathematical structure.
The iteration process tracks how quickly a complex number's sequence diverges, with a maximum iteration threshold determining set membership. By systematically testing each point's convergence behavior, we can map the set's intricate boundary conditions.
I'll create coordinate arrays using NumPy's linspace, then construct a meshgrid for efficient vectorized computation. The algorithm will track each point's trajectory, marking iteration counts and identifying divergence patterns through a sophisticated masking technique.
The smooth coloring approach involves logarithmic transformations to capture nuanced escape time characteristics, carefully handling potential numerical edge cases by suppressing divide-by-zero warnings.
Visualization involves rendering the iteration data as an image, with careful axis labeling and a color bar to represent computational complexity. The plot uses a 'hot' colormap to highlight divergence regions, providing an intuitive view of the set's intricate boundary dynamics.
The code prepares for transitioning to exploring Julia set variations, suggesting a systematic approach to fractal visualization techniques.
I'll generate a Julia set representation, mapping complex plane behavior where a constant parameter defines the set's unique geometric characteristics. The implementation will explore how different complex constants create distinctive fractal patterns, revealing underlying mathematical structures through visual exploration.
I'll use NumPy to create coordinate meshgrids, systematically iterating through complex plane points. Each point undergoes recursive transformation, tracking iteration counts to visualize escape velocities and intricate boundary behaviors.
The visualization process involves tracking point trajectories, determining which regions converge or diverge under repeated complex quadratic transformations. By mapping iteration counts, I'll generate a detailed fractal image revealing the set's intricate geometric boundaries.
I'll apply a sophisticated smoothing technique to enhance visual detail, using the twilight colormap to highlight subtle iteration variations. The resulting plot will display real and imaginary axes, providing a comprehensive view of the Julia set's complex dynamics.
The colorbar will quantify iteration counts, offering insight into the mathematical structure underlying this mesmerizing geometric pattern.
The visualization captures the intricate behavior of the specific complex parameter c, revealing the set's delicate fractal boundaries through a carefully calibrated color gradient.
For the Barnsley Fern implementation, I'll generate a precise point distribution using probabilistic affine transformations. These transformations will systematically construct the iconic fractal's intricate leaf-like structure, mapping geometric variations through carefully weighted random selections.
The function will initialize coordinate arrays to capture the fern's emergent geometric complexity, preparing for a detailed point generation process that mimics natural botanical growth patterns.
I'll start by establishing initial coordinates at the origin, then apply a nuanced probabilistic selection mechanism to determine each subsequent point's precise location through four distinct transformation rules.
The randomized selection will drive the point generation, with each transformation representing a specific geometric region of the fern - from the central stem to the delicate left and right leaflets, creating a mathematically elegant representation of natural growth.
By mapping points through these carefully calibrated linear transformations and leveraging a color gradient based on vertical positioning, I'll generate a visually compelling botanical simulation that captures the intricate fractal geometry of a fern's structural development.
The visualization will employ a dark background to accentuate the verdant green color palette, rendering the mathematical abstraction with organic, lifelike nuance.
I'll configure the plot to eliminate axes, ensuring an uninterrupted view of the emergent geometric pattern, and utilize tight layout parameters to maximize visual impact.
The recursive function systematically subdivides the initial square into nine equal segments, strategically removing the central square while recursively processing the surrounding eight squares. Each iteration reduces the square's size proportionally, creating an intricate fractal structure with progressively diminishing geometric elements.
I'll generate the Sierpinski Carpet by invoking the recursive drawing method, specifying the desired recursion depth to control the fractal's complexity and visual intricacy.
The visualization parameters ensure a centered, symmetrical representation with precise axis limits, maintaining the geometric proportions and aesthetic balance of the mathematical pattern.
I'll complete the coordinate conversion process for the Hilbert curve, tracking the transformation of index values into precise spatial coordinates through an iterative rotation mechanism.
The rotation function handles quadrant-specific transformations, strategically flipping and repositioning coordinates based on specific geometric rules that preserve the curve's intricate self-similar structure.
I'll generate the Hilbert curve visualization by establishing a grid resolution determined by the specified order, preparing to map the curve's complex traversal across a two-dimensional space.
I create coordinate sequences through a systematic mapping process, translating distance values into precise x and y positions. By leveraging a color gradient, I'll render the curve's progression using a line collection that elegantly displays the curve's continuous path, with each segment smoothly transitioning through the viridis color spectrum.
The visualization will automatically scale to accommodate the curve's full geometric extent, revealing its fascinating spatial characteristics.
I'll set a square aspect ratio to preserve the curve's intrinsic geometric proportions, adding a descriptive title that highlights the curve's mathematical order. Removing axis markings ensures a clean, focused presentation of the fractal's pure geometric structure.
The gallery generation method will systematically construct multiple fractal representations, beginning with a Sierpinski triangle rendered through recursive vertex transformations.
I'll define precise coordinate limits to frame the triangle symmetrically, ensuring visual balance. The aspect ratio constraint maintains geometric fidelity, while disabling axis lines keeps the focus on the intricate fractal pattern. The next visualization will explore the Koch snowflake's elegant geometric recursion, using trigonometric calculations to position initial vertices.
I'll extract x and y coordinates from the generated points, plotting a delicate blue line that traces the snowflake's boundary. A subtle cyan fill adds depth without overwhelming the geometric precision. The equal aspect ratio preserves the fractal's inherent symmetry, and removing axis markings emphasizes the pure mathematical form.
The fractal tree will emerge from a strategic origin point, using recursive angle transformations to generate branching structures. Carefully chosen coordinate limits will frame the tree's expansive growth, allowing the intricate branching pattern to develop with mathematical elegance.
Next, I'll visualize the Mandelbrot set using complex number computations. By mapping coordinates and iteratively testing point convergence, I'll generate a heat-mapped representation revealing the set's intricate boundary dynamics. The color gradient will highlight the mathematical complexity of this iconic fractal.
The Julia set preparation begins, suggesting another layer of complex mathematical visualization awaits, with a specific complex constant about to define its unique geometric characteristics.
I'll plot the Julia set using a similar computational approach, mapping complex plane coordinates and tracking point behavior under iterative transformation. The twilight color palette will provide a nuanced view of the set's intricate structural patterns.
A Barnsley fern will complete the visualization series, introducing a natural fractal generated through precise geometric transformations. I'll use a dark background to emphasize the delicate green fractal structure, creating a striking visual representation of mathematical recursion.
The visualization concludes with a comprehensive title highlighting the recursive algorithmic foundations underlying these mesmerizing geometric patterns.
The main function will present an interactive menu, offering users a selection of six distinct fractal visualizations spanning geometric, natural, and complex mathematical representations.
Users can navigate through options like Sierpinski Triangle, Koch Snowflake, and Fractal Tree, with an intuitive interface allowing depth customization for each recursive pattern. The menu provides recommended depth ranges to help users generate visually compelling fractal representations.
The interactive selection process enables exploration of intricate mathematical landscapes, inviting users to experiment with different recursive generation techniques and observe emerging complex structures.
Depth parameters control the level of detail, while some fractals like the Mandelbrot set introduce additional configuration through maximum iteration settings, offering nuanced visual exploration.
I'll parse the complex number input, allowing users to select predefined Julia set configurations or craft custom complex parameters. The menu presents intriguing preset values representing distinct fractal morphologies - from spiraling patterns to dendrite-like structures and galactic formations.
The input mechanism supports both preset selections and manual complex number entry, enabling flexible mathematical visualization.
If a custom input fails validation, the system defaults to a spiral-like configuration. After parameter selection, the program triggers the Julia set plotting function, dynamically rendering the chosen fractal landscape.
The subsequent menu options explore additional generative art techniques, including Barnsley fern generation, Sierpinski carpet rendering, and Hilbert curve visualization, each with configurable parameters to control complexity and detail.
When the user selects the gallery option or chooses to exit, the program either launches a comprehensive fractal display or gracefully terminates with a farewell message, handling potential input errors through robust validation mechanisms.</think> # Fractal Visualization with Recursive Algorithms
This comprehensive Python implementation demonstrates various fractals using recursive algorithms with detailed explanations.
## Complete Implementation
```python
"""
Fractal Visualization using Recursive Algorithms
================================================
Demonstrates:
1. Sierpinski Triangle
2. Koch Snowflake
3. Fractal Tree
4. Dragon Curve
5. Mandelbrot Set
6. Julia Set
7. Barnsley Fern
8. Sierpinski Carpet
9. Hilbert Curve
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.patches import Polygon, Rectangle
from typing import List, Tuple
import warnings
warnings.filterwarnings('ignore')
# ════════════════════════════════════════════════════════════════════════════
# 1. SIERPINSKI TRIANGLE
# ════════════════════════════════════════════════════════════════════════════
class SierpinskiTriangle:
"""
Sierpinski Triangle - A fractal created by recursive subdivision.
Algorithm:
1. Start with an equilateral triangle
2. Find midpoints of each edge
3. Connect midpoints to form 4 smaller triangles
4. Remove the center triangle
5. Repeat for remaining 3 triangles
Complexity: O(3^n) triangles at depth n
"""
def __init__(self, depth: int = 6):
self.depth = depth
self.triangles = []
def generate(self, vertices: List[Tuple[float, float]], depth: int) -> None:
"""Recursively generate triangle vertices."""
if depth == 0:
self.triangles.append(vertices)
return
# Calculate midpoints
p0, p1, p2 = vertices
mid01 = ((p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2)
mid12 = ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2)
mid20 = ((p2[0] + p0[0]) / 2, (p2[1] + p0[1]) / 2)
# Recurse on 3 corner triangles (skip center)
self.generate([p0, mid01, mid20], depth - 1)
self.generate([mid01, p1, mid12], depth - 1)
self.generate([mid20, mid12, p2], depth - 1)
def plot(self, ax: plt.Axes = None, colormap: str = 'viridis') -> None:
"""Visualize the Sierpinski Triangle."""
if ax is None:
fig, ax = plt.subplots(figsize=(10, 9))
# Generate triangles
self.triangles = []
height = np.sqrt(3) / 2
initial_vertices = [(0, 0), (1, 0), (0.5, height)]
self.generate(initial_vertices, self.depth)
# Plot each triangle with color
cmap = plt.get_cmap(colormap)
for i, tri in enumerate(self.triangles):
color = cmap(i / len(self.triangles))
polygon = Polygon(tri, facecolor=color, edgecolor='black',
linewidth=0.3, alpha=0.8)
ax.add_patch(polygon)
ax.set_xlim(-0.05, 1.05)
ax.set_ylim(-0.05, 0.95)
ax.set_aspect('equal')
ax.set_title(f'Sierpinski Triangle (Depth: {self.depth})\n'
f'Number of triangles: {len(self.triangles)}', fontsize=12)
ax.axis('off')
# ════════════════════════════════════════════════════════════════════════════
# 2. KOCH SNOWFLAKE
# ════════════════════════════════════════════════════════════════════════════
class KochSnowflake:
"""
Koch Snowflake - Infinite perimeter, finite area.
Algorithm:
For each line segment:
1. Divide into 3 equal parts
2. Replace middle segment with 2 sides of equilateral triangle
3. Repeat recursively
Properties:
- Perimeter: (4/3)^n × initial perimeter (infinite as n→∞)
- Area: 8/5 × initial triangle area (finite limit)
"""
def __init__(self, depth: int = 4):
self.depth = depth
def koch_curve(self, p1: Tuple[float, float],
p2: Tuple[float, float], depth: int) -> List[Tuple[float, float]]:
"""Generate points along a Koch curve segment."""
if depth == 0:
return [p1, p2]
# Calculate division points
dx, dy = p2[0] - p1[0], p2[1] - p1[1]
# Points at 1/3 and 2/3
a = (p1[0] + dx/3, p1[1] + dy/3)
b = (p1[0] + 2*dx/3, p1[1] + 2*dy/3)
# Peak point (rotate 60° from point a)
angle = np.pi / 3
peak = (
a[0] + (dx/3) * np.cos(angle) - (dy/3) * np.sin(angle),
a[1] + (dx/3) * np.sin(angle) + (dy/3) * np.cos(angle)
)
# Recursive subdivision
curve = []
for start, end in [(p1, a), (a, peak), (peak, b), (b, p2)]:
segment = self.koch_curve(start, end, depth - 1)
curve.extend(segment[:-1])
curve.append(p2)
return curve
def plot(self, ax: plt.Axes = None) -> None:
"""Visualize the Koch Snowflake."""
if ax is None:
fig, ax = plt.subplots(figsize=(10, 10))
# Initial equilateral triangle vertices
vertices = []
for i in range(3):
angle = np.pi/2 + i * 2*np.pi/3
vertices.append((np.cos(angle), np.sin(angle)))
# Generate Koch curve for each edge
all_points = []
for i in range(3):
points = self.koch_curve(vertices[i], vertices[(i+1) % 3], self.depth)
all_points.extend(points[:-1])
all_points.append(all_points[0])
# Plot with gradient coloring
x = [p[0] for p in all_points]
y = [p[1] for p in all_points]
# Create colored segments
segments = [[(all_points[i][0], all_points[i][1]),
(all_points[i+1][0], all_points[i+1][1])]
for i in range(len(all_points)-1)]
colors = plt.cm.rainbow(np.linspace(0, 1, len(segments)))
lc = LineCollection(segments, colors=colors, linewidth=1)
ax.add_collection(lc)
# Fill interior
ax.fill(x, y, alpha=0.2, color='cyan')
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_aspect('equal')
ax.set_title(f'Koch Snowflake (Depth: {self.depth})\n'
f'Segments: {len(segments)}', fontsize=12)
ax.axis('off')
# ════════════════════════════════════════════════════════════════════════════
# 3. FRACTAL TREE
# ════════════════════════════════════════════════════════════════════════════
class FractalTree:
"""
Fractal Tree - Binary branching pattern.
Algorithm:
1. Draw trunk
2. At end of branch, split into 2 branches
3. Each branch is shorter and rotated
4. Repeat recursively
Parameters affect tree appearance:
- branch_angle: angle between branches
- length_ratio: branch length reduction per level
"""
def __init__(self, depth: int = 10, branch_angle: float = 25,
length_ratio: float = 0.7):
self.depth = depth
self.branch_angle = branch_angle
self.length_ratio = length_ratio
self.lines = []
def generate_branch(self, x: float, y: float, angle: float,
length: float, depth: int) -> None:
"""Recursively generate tree branches."""
if depth == 0:
return
# Calculate branch endpoint
angle_rad = np.radians(angle)
x_end = x + length * np.cos(angle_rad)
y_end = y + length * np.sin(angle_rad)
# Store branch with depth info for coloring
self.lines.append({
'start': (x, y),
'end': (x_end, y_end),
'depth': depth,
'length': length
})
# Generate child branches
new_length = length * self.length_ratio
# Right branch
self.generate_branch(x_end, y_end, angle + self.branch_angle,
new_length, depth - 1)
# Left branch
self.generate_branch(x_end, y_end, angle - self.branch_angle,
new_length, depth - 1)
def plot(self, ax: plt.Axes = None) -> None:
"""Visualize the fractal tree."""
if ax is None:
fig, ax = plt.subplots(figsize=(12, 10))
# Set background
ax.set_facecolor('#87CEEB') # Sky blue
# Generate tree
self.lines = []
self.generate_branch(0, 0, 90, 80, self.depth)
# Draw ground
ax.axhspan(-30, 0, color='#228B22', alpha=0.6)
# Draw branches with appropriate styling
for line in self.lines:
if line['depth'] > 3:
color = '#8B4513' # Brown (trunk/branches)
width = line['depth'] * 0.7
else:
color = '#228B22' # Green (leaves)
width = line['depth'] * 0.5
ax.plot([line['start'][0], line['end'][0]],
[line['start'][1], line['end'][1]],
color=color, linewidth=width,
solid_capstyle='round')
ax.set_xlim(-150, 150)
ax.set_ylim(-20, 200)
ax.set_aspect('equal')
ax.set_title(f'Fractal Tree (Depth: {self.depth}, '
f'Angle: {self.branch_angle}°)', fontsize=12)
ax.axis('off')
# ════════════════════════════════════════════════════════════════════════════
# 4. DRAGON CURVE
# ════════════════════════════════════════════════════════════════════════════
class DragonCurve:
"""
Dragon Curve - Space-filling curve with self-similarity.
L-System Rules:
- Axiom: FX
- X → X+YF+
- Y → -FX-Y
- F: move forward
- +: turn right 90°
- -: turn left 90°
The dragon curve tiles the plane and appears in Jurassic Park!
"""
def __init__(self, depth: int = 12):
self.depth = depth
def generate_lsystem(self) -> str:
"""Generate L-system string through recursive expansion."""
def expand(s: str, n: int) -> str:
if n == 0:
return s
result = ""
for char in s:
if char == 'X':
result += 'X+YF+'
elif char == 'Y':
result += '-FX-Y'
else:
result += char
return expand(result, n - 1)
return expand('FX', self.depth)
def interpret_lsystem(self, instructions: str) -> List[Tuple[float, float]]:
"""Convert L-system instructions to coordinates."""
points = [(0, 0)]
x, y, angle = 0, 0, 0
for char in instructions:
if char == 'F':
x += np.cos(np.radians(angle))
y += np.sin(np.radians(angle))
points.append((x, y))
elif char == '+':
angle += 90
elif char == '-':
angle -= 90
return points
def plot(self, ax: plt.Axes = None) -> None:
"""Visualize the dragon curve."""
if ax is None:
fig, ax = plt.subplots(figsize=(12, 12))
# Generate curve
instructions = self.generate_lsystem()
points = self.interpret_lsystem(instructions)
# Create line segments with rainbow colors
segments = [[(points[i][0], points[i][1]),
(points[i+1][0], points[i+1][1])]
for i in range(len(points) - 1)]
colors = plt.cm.hsv(np.linspace(0, 1, len(segments)))
lc = LineCollection(segments, colors=colors, linewidth=0.5)
ax.add_collection(lc)
ax.autoscale()
ax.set_aspect('equal')
ax.set_title(f'Dragon Curve (Depth: {self.depth})\n'
f'Segments: {len(segments)}', fontsize=12)
ax.axis('off')
# ════════════════════════════════════════════════════════════════════════════
# 5. MANDELBROT SET
# ════════════════════════════════════════════════════════════════════════════
class MandelbrotSet:
"""
Mandelbrot Set - The most famous fractal.
Definition:
Set of complex numbers c for which the iteration:
z_{n+1} = z_n² + c (starting with z_0 = 0)
remains bounded (|z| ≤ 2).
The boundary has infinite complexity and contains
miniature copies of the whole set.
"""
def __init__(self, max_iter: int = 100,
bounds: Tuple[float, float, float, float] = (-2.5, 1.0, -1.25, 1.25)):
self.max_iter = max_iter
self.xmin, self.xmax, self.ymin, self.ymax = bounds
def compute(self, width: int = 800, height: int = 600) -> np.ndarray:
"""Compute escape times for each pixel."""
x = np.linspace(self.xmin, self.xmax, width)
y = np.linspace(self.ymin, self.ymax, height)
X, Y = np.meshgrid(x, y)
C = X + 1j * Y
Z = np.zeros_like(C)
M = np.zeros(C.shape)
for i in range(self.max_iter):
mask = np.abs(Z) <= 2
Z[mask] = Z[mask] ** 2 + C[mask]
M[mask] = i
# Smooth coloring
with np.errstate(divide='ignore', invalid='ignore'):
smooth = M + 1 - np.log2(np.log2(np.abs(Z) + 1e-10))
smooth = np.nan_to_num(smooth, nan=self.max_iter)
return smooth
def plot(self, ax: plt.Axes = None, cmap: str = 'hot') -> None:
"""Visualize the Mandelbrot set."""
if ax is None:
fig, ax = plt.subplots(figsize=(12, 9))
data = self.compute()
im = ax.imshow(data, extent=[self.xmin, self.xmax, self.ymin, self.ymax],
cmap=cmap, origin='lower', aspect='equal')
ax.set_xlabel('Re(c)', fontsize=10)
ax.set_ylabel('Im(c)', fontsize=10)
ax.set_title(f'Mandelbrot Set (Max Iterations: {self.max_iter})', fontsize=12)
plt.colorbar(im, ax=ax, label='Iterations', shrink=0.8)
# ════════════════════════════════════════════════════════════════════════════
# 6. JULIA SET
# ════════════════════════════════════════════════════════════════════════════
class JuliaSet:
"""
Julia Set - Family of fractals related to Mandelbrot.
Difference from Mandelbrot:
- Mandelbrot: c varies, z_0 = 0
- Julia: c is fixed, z_0 varies
Famous c values:
- c = -0.7 + 0.27015i (spiral)
- c = -0.8 + 0.156i (dendrite)
- c = -0.4 + 0.6i (rabbit)
- c = 0.285 + 0.01i (galaxy)
"""
PRESETS = {
'spiral': complex(-0.7, 0.27015),
'dendrite': complex(-0.8, 0.156),
'rabbit': complex(-0.4, 0.6),
'galaxy': complex(0.285, 0.01),
'lightning': complex(-0.1, 0.651)
}
def __init__(self, c: complex = None, preset: str = 'spiral',
max_iter: int = 200):
self.c = c if c else self.PRESETS.get(preset, self.PRESETS['spiral'])
self.max_iter = max_iter
def compute(self, width: int = 800, height: int = 600,
bounds: Tuple[float, float, float, float] = (-2, 2, -1.5, 1.5)) -> np.ndarray:
"""Compute the Julia set."""
xmin, xmax, ymin, ymax = bounds
x = np.linspace(xmin, xmax, width)
y = np.linspace(ymin, ymax, height)
X, Y = np.meshgrid(x, y)
Z = X + 1j * Y
M = np.zeros(Z.shape)
for i in range(self.max_iter):
mask = np.abs(Z) <= 2
Z[mask] = Z[mask] ** 2 + self.c
M[mask] = i
return M
def plot(self, ax: plt.Axes = None, cmap: str = 'twilight_shifted') -> None:
"""Visualize the Julia set."""
if ax is None:
fig, ax = plt.subplots(figsize=(12, 9))
data = self.compute()
im = ax.imshow(data, extent=[-2, 2, -1.5, 1.5],
cmap=cmap, origin='lower', aspect='equal')
ax.set_xlabel('Re(z)', fontsize=10)
ax.set_ylabel('Im(z)', fontsize=10)
ax.set_title(f'Julia Set: c = {self.c.real:.4f} + {self.c.imag:.4f}i',
fontsize=12)
plt.colorbar(im, ax=ax, label='Iterations', shrink=0.8)
# ════════════════════════════════════════════════════════════════════════════
# 7. BARNSLEY FERN
# ════════════════════════════════════════════════════════════════════════════
class BarnsleyFern:
"""
Barnsley Fern - Iterated Function System (IFS) fractal.
Uses 4 affine transformations applied randomly:
1. Stem (1%): Draws the stem
2. Main frond (85%): Draws successively smaller leaflets
3. Left leaflet (7%): Draws largest left-hand leaflet
4. Right leaflet (7%): Draws largest right-hand leaflet
The probability distribution creates a realistic fern shape.
"""
def __init__(self, n_points: int = 100000):
self.n_points = n_points
# Transformation coefficients [a, b, c, d, e, f, probability]
self.transforms = [
# Stem
{'a': 0, 'b': 0, 'c': 0, 'd': 0.16, 'e': 0, 'f': 0, 'p': 0.01},
# Main
{'a': 0.85, 'b': 0.04, 'c': -0.04, 'd': 0.85, 'e': 0, 'f': 1.6, 'p': 0.85},
# Left
{'a': 0.2, 'b': -0.26, 'c': 0.23, 'd': 0.22, 'e': 0, 'f': 1.6, 'p': 0.07},
# Right
{'a': -0.15, 'b': 0.28, 'c': 0.26, 'd': 0.24, 'e': 0, 'f': 0.44, 'p': 0.07}
]
def generate(self) -> Tuple[np.ndarray, np.ndarray]:
"""Generate fern points using IFS."""
x = np.zeros(self.n_points)
y = np.zeros(self.n_points)
for i in range(1, self.n_points):
r = np.random.random()
# Select transformation based on probability
cumprob = 0
for t in self.transforms:
cumprob += t['p']
if r < cumprob:
x[i] = t['a'] * x[i-1] + t['b'] * y[i-1] + t['e']
y[i] = t['c'] * x[i-1] + t['d'] * y[i-1] + t['f']
break
return x, y
def plot(self, ax: plt.Axes = None) -> None:
"""Visualize the Barnsley fern."""
if ax is None:
fig, ax = plt.subplots(figsize=(8, 12))
ax.set_facecolor('#1a1a2e')
x, y = self.generate()
# Color by height
colors = plt.cm.Greens(0.3 + 0.7 * (y - y.min()) / (y.max() - y.min() + 1e-10))
ax.scatter(x, y, c=colors, s=0.1, marker='.')
ax.set_aspect('equal')
ax.set_title(f'Barnsley Fern ({self.n_points:,} points)', fontsize=12)
ax.axis('off')
# ════════════════════════════════════════════════════════════════════════════
# 8. SIERPINSKI CARPET
# ════════════════════════════════════════════════════════════════════════════
class SierpinskiCarpet:
"""
Sierpinski Carpet - 2D generalization of Cantor set.
Algorithm:
1. Divide square into 9 equal sub-squares (3×3 grid)
2. Remove the center square
3. Apply recursively to remaining 8 squares
Properties:
- Fractal dimension: log(8)/log(3) ≈ 1.893
- Self-similar at all scales
"""
def __init__(self, depth: int = 4):
self.depth = depth
self.squares = []
def generate(self, x: float, y: float, size: float, depth: int) -> None:
"""Recursively generate carpet squares."""
if depth == 0:
self.squares.append((x, y, size))
return
new_size = size / 3
for i in range(3):
for j in range(3):
if not (i == 1 and j == 1): # Skip center
self.generate(x + i * new_size, y + j * new_size,
new_size, depth - 1)
def plot(self, ax: plt.Axes = None, cmap: str = 'plasma') -> None:
"""Visualize the Sierpinski carpet."""
if ax is None:
fig, ax = plt.subplots(figsize=(10, 10))
ax.set_facecolor('black')
self.squares = []
self.generate(0, 0, 1, self.depth)
cmap_func = plt.get_cmap(cmap)
for i, (x, y, size) in enumerate(self.squares):
color = cmap_func(np.random.random())
rect = Rectangle((x, y), size, size,
facecolor=color, edgecolor='none')
ax.add_patch(rect)
ax.set_xlim(-0.02, 1.02)
ax.set_ylim(-0.02, 1.02)
ax.set_aspect('equal')
ax.set_title(f'Sierpinski Carpet (Depth: {self.depth})\n'
f'Squares: {len(self.squares)}', fontsize=12)
ax.axis('off')
# ════════════════════════════════════════════════════════════════════════════
# 9. HILBERT CURVE
# ════════════════════════════════════════════════════════════════════════════
class HilbertCurve:
"""
Hilbert Curve - Space-filling curve.
Properties:
- Visits every point in a square grid exactly once
- Preserves locality: nearby points on curve are nearby in space
- Used in database indexing, image processing
The curve is defined recursively by rotating and connecting
smaller Hilbert curves.
"""
def __init__(self, order: int = 5):
self.order = order
self.n = 2 ** order
def d2xy(self, d: int) -> Tuple[int, int]:
"""Convert 1D Hilbert index to 2D coordinates."""
x = y = 0
s = 1
while s < self.n:
rx = 1 & (d // 2)
ry = 1 & (d ^ rx)
# Rotate quadrant
if ry == 0:
if rx == 1:
x = s - 1 - x
y = s - 1 - y
x, y = y, x
x += s * rx
y += s * ry
d //= 4
s *= 2
return x, y
def generate(self) -> List[Tuple[int, int]]:
"""Generate all points along the Hilbert curve."""
return [self.d2xy(d) for d in range(self.n * self.n)]
def plot(self, ax: plt.Axes = None, cmap: str = 'viridis') -> None:
"""Visualize the Hilbert curve."""
if ax is None:
fig, ax = plt.subplots(figsize=(10, 10))
points = self.generate()
# Create line segments
segments = [[(points[i][0], points[i][1]),
(points[i+1][0], points[i+1][1])]
for i in range(len(points) - 1)]
colors = plt.cm.get_cmap(cmap)(np.linspace(0, 1, len(segments)))
lc = LineCollection(segments, colors=colors, linewidth=1.5)
ax.add_collection(lc)
ax.autoscale()
ax.set_aspect('equal')
ax.set_title(f'Hilbert Curve (Order: {self.order})\n'
f'Grid: {self.n}×{self.n}', fontsize=12)
ax.axis('off')
# ════════════════════════════════════════════════════════════════════════════
# GALLERY AND DEMONSTRATION
# ════════════════════════════════════════════════════════════════════════════
def create_fractal_gallery():
"""Create a comprehensive gallery of all fractals."""
fig = plt.figure(figsize=(20, 16))
fig.suptitle('Fractal Gallery - Recursive Algorithms', fontsize=18, y=0.98)
# Create grid
gs = fig.add_gridspec(3, 3, hspace=0.3, wspace=0.2)
# 1. Sierpinski Triangle
ax1 = fig.add_subplot(gs[0, 0])
SierpinskiTriangle(depth=5).plot(ax1)
# 2. Koch Snowflake
ax2 = fig.add_subplot(gs[0, 1])
KochSnowflake(depth=4).plot(ax2)
# 3. Fractal Tree
ax3 = fig.add_subplot(gs[0, 2])
FractalTree(depth=9).plot(ax3)
# 4. Dragon Curve
ax4 = fig.add_subplot(gs[1, 0])
DragonCurve(depth=11).plot(ax4)
# 5. Mandelbrot Set
ax5 = fig.add_subplot(gs[1, 1])
MandelbrotSet(max_iter=80).plot(ax5)
# 6. Julia Set
ax6 = fig.add_subplot(gs[1, 2])
JuliaSet(preset='spiral').plot(ax6)
# 7. Barnsley Fern
ax7 = fig.add_subplot(gs[2, 0])
BarnsleyFern(n_points=50000).plot(ax7)
# 8. Sierpinski Carpet
ax8 = fig.add_subplot(gs[2, 1])
SierpinskiCarpet(depth=4).plot(ax8)
# 9. Hilbert Curve
ax9 = fig.add_subplot(gs[2, 2])
HilbertCurve(order=5).plot(ax9)
plt.tight_layout(rect=[0, 0, 1, 0.96])
plt.savefig('fractal_gallery.png', dpi=150, bbox_inches='tight')
plt.show()
def demonstrate_fractal(fractal_type: str, **kwargs):
"""Demonstrate a specific fractal with custom parameters."""
fractals = {
'sierpinski': SierpinskiTriangle,
'koch': KochSnowflake,
'tree': FractalTree,
'dragon': DragonCurve,
'mandelbrot': MandelbrotSet,
'julia': JuliaSet,
'fern': BarnsleyFern,
'carpet': SierpinskiCarpet,
'hilbert': HilbertCurve
}
if fractal_type.lower() not in fractals:
print(f"Unknown fractal: {fractal_type}")
print(f"Available: {', '.join(fractals.keys())}")
return
fractal = fractals[fractal_type.lower()](**kwargs)
fractal.plot()
plt.show()
# ════════════════════════════════════════════════════════════════════════════
# INTERACTIVE MENU
# ════════════════════════════════════════════════════════════════════════════
def interactive_menu():
"""Run interactive demonstration."""
print("\n" + "═" * 60)
print(" FRACTAL VISUALIZATION - RECURSIVE ALGORITHMS")
print("═" * 60)
print("""
Available Fractals:
─────────────────────────────────────────────────
1. Sierpinski Triangle │ 6. Julia Set
2. Koch Snowflake │ 7. Barnsley Fern
3. Fractal Tree │ 8. Sierpinski Carpet
4. Dragon Curve │ 9. Hilbert Curve
5. Mandelbrot Set │ 0. Full Gallery
─────────────────────────────────────────────────
Enter 'q' to quit
""")
while True:
choice = input("\n► Select fractal (0-9, q): ").strip().lower()
if choice == 'q':
print("\n✓ Thanks for exploring fractals!\n")
break
elif choice == '0':
create_fractal_gallery()
elif choice == '1':
d = int(input(" Depth (1-8) [6]: ") or 6)
demonstrate_fractal('sierpinski', depth=min(d, 8))
elif choice == '2':
d = int(input(" Depth (1-5) [4]: ") or 4)
demonstrate_fractal('koch', depth=min(d, 5))
elif choice == '3':
d = int(input(" Depth (1-12) [10]: ") or 10)
a = float(input(" Branch angle (15-45) [25]: ") or 25)
demonstrate_fractal('tree', depth=min(d, 12), branch_angle=a)
elif choice == '4':
d = int(input(" Depth (1-15) [12]: ") or 12)
demonstrate_fractal('dragon', depth=min(d, 15))
elif choice == '5':
m = int(input(" Max iterations (50-500) [100]: ") or 100)
demonstrate_fractal('mandelbrot', max_iter=min(m, 500))
elif choice == '6':
print(" Presets: spiral, dendrite, rabbit, galaxy, lightning")
p = input(" Preset [spiral]: ") or 'spiral'
demonstrate_fractal('julia', preset=p)
elif choice == '7':
n = int(input(" Points (10000-200000) [100000]: ") or 100000)
demonstrate_fractal('fern', n_points=min(n, 200000))
elif choice == '8':
d = int(input(" Depth (1-5) [4]: ") or 4)
demonstrate_fractal('carpet', depth=min(d, 5))
elif choice == '9':
o = int(input(" Order (1-7) [5]: ") or 5)
demonstrate_fractal('hilbert', order=min(o, 7))
else:
print(" ✗ Invalid choice. Enter 0-9 or 'q'.")
# ════════════════════════════════════════════════════════════════════════════
# MAIN EXECUTION
# ════════════════════════════════════════════════════════════════════════════
if __name__ == "__main__":
# Quick demo - create gallery
print("Creating fractal gallery...")
create_fractal_gallery()
# Or run interactive menu
# interactive_menu()