Creating fractal visualizations
The user wants Python code to visualize fractals using recursion, which is a fun but open-ended request! I think it makes sense to provide a couple of examples, like the Sierpinski triangle and a fractal tree, since they explicitly ask for recursive algorithms. We can use libraries like matplotlib or turtle for visualization, but matplotlib is likely better for a non-interactive environment. I should keep the code concise but functional, maybe with a small framework to switch between fractals.Designing fractal code
For visualizing fractals, I think using matplotlib is a solid choice. I’m thinking of including a minimal explanation followed by complete code. For the fractal tree, I can create a function that recursively draws branches until reaching a base case. Similarly, for the Sierpinski triangle, I could draw filled triangles and recursively call the function on subtriangles. To keep things organized, I'll offer two independent code blocks so the user can run each fractal individually. Commenting within the code could add clarity, too!Providing fractal code
The user asked for "Create Python code," so I can deliver a single script containing multiple fractal examples with a simple command-line interface (CLI). However, since I don't know their environment, it might be better to keep things straightforward by providing two separate, self-contained code blocks. This way, the user can easily run each example without dealing with any complications. It feels like a good way to satisfy their request!Clarifying recursion and visualization
I want to focus on ensuring the recursion is clear and the visualization works well. For the first example, I’ll create a fractal tree using matplotlib. The pseudocode shows how to set up drawing branches recursively, with parameters for length, angle, depth, and branch width. I’ll establish a base case and then create two new branches at each step. In the main call, I want to set up the figure and adjust coordinate ranges to make the trunk vertical and centered.Creating the Sierpinski triangle
For the second example, I’ll define the function for drawing the Sierpinski triangle. It starts by taking the polygon's vertices and filling it. In the recursive function, if the depth is zero, it fills the triangle; otherwise, it calculates the midpoints and recursively calls for smaller triangles. I’ll set up the vertices for a large equilateral triangle and ensure the axis is adjusted properly. I’ll keep the explanation concise and focus on the two examples: the fractal tree and the Sierpinski triangle. It’s also a good idea to mention how to adjust recursion depth for more detail. Here are two small, self-contained examples of recursive fractals in Python using matplotlib:
- Fractal Tree (binary tree)
- Sierpinski Triangle
Install matplotlib if needed:
pip install matplotlib
1. Fractal Tree (recursive branching)
import math
import matplotlib.pyplot as plt
def draw_branch(ax, x, y, length, angle, depth, width=2):
"""
Recursively draw a fractal tree branch.
ax : Matplotlib Axes
x, y : starting point
length : length of the branch
angle : direction (radians)
depth : recursion depth
width : line width
"""
if depth == 0 or length < 0.01:
return
# Compute end point of this branch
x2 = x + length * math.cos(angle)
y2 = y + length * math.sin(angle)
# Draw the branch
ax.plot([x, x2], [y, y2], color="brown", linewidth=width)
# Parameters for sub-branches
new_length = length * 0.7
new_width = width * 0.7
angle_delta = math.radians(30)
# Left and right branches (recursive calls)
draw_branch(ax, x2, y2, new_length, angle + angle_delta, depth - 1, new_width)
draw_branch(ax, x2, y2, new_length, angle - angle_delta, depth - 1, new_width)
def main():
fig, ax = plt.subplots(figsize=(6, 8))
ax.set_aspect("equal")
ax.axis("off")
# Start at (0, 0), pointing straight up (pi/2 radians)
draw_branch(ax, x=0.0, y=0.0, length=1.0, angle=math.pi/2, depth=10, width=4)
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(0, 2.2)
plt.tight_layout()
plt.show()
if __name__ == "__main__":
main()
Adjust depth in draw_branch(...) to change how detailed the tree is.
2. Sierpinski Triangle (recursive subdivision)
import math
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
def draw_filled_triangle(ax, vertices, color="black"):
"""
Draw a filled triangle defined by its 3 vertices.
vertices: list of (x, y) tuples
"""
triangle = Polygon(vertices, closed=True, edgecolor="black", facecolor=color)
ax.add_patch(triangle)
def sierpinski(ax, vertices, depth):
"""
Recursively draw a Sierpinski triangle.
vertices: list of 3 (x, y) tuples
depth : recursion depth
"""
if depth == 0:
draw_filled_triangle(ax, vertices, color="purple")
return
# Unpack vertices
(x1, y1), (x2, y2), (x3, y3) = vertices
# Midpoints of each side
m12 = ((x1 + x2) / 2, (y1 + y2) / 2)
m23 = ((x2 + x3) / 2, (y2 + y3) / 2)
m31 = ((x3 + x1) / 2, (y3 + y1) / 2)
# Recursive calls for the 3 corner triangles
sierpinski(ax, [ (x1, y1), m12, m31 ], depth - 1)
sierpinski(ax, [ (x2, y2), m23, m12 ], depth - 1)
sierpinski(ax, [ (x3, y3), m31, m23 ], depth - 1)
def main():
fig, ax = plt.subplots(figsize=(6, 6))
ax.set_aspect("equal")
ax.axis("off")
# Coordinates of a large equilateral triangle
# Base from (0, 0) to (1, 0), top at (0.5, sqrt(3)/2)
h = math.sqrt(3) / 2
vertices = [(0.0, 0.0), (1.0, 0.0), (0.5, h)]
sierpinski(ax, vertices, depth=6) # increase/decrease depth to change detail
ax.set_xlim(-0.1, 1.1)
ax.set_ylim(-0.1, h + 0.1)
plt.tight_layout()
plt.show()
if __name__ == "__main__":
main()
If you tell me which kind of fractal you’re most interested in (trees, snowflakes, Cantor sets, etc.), I can tailor or extend the code to that specific pattern.