import numpy as np
import matplotlib.pyplot as plt
def dragon_curve(iterations):
points = np.array([[0, 0], [1, 0]])
direction = np.array([[0, -1], [1, 0]])
for _ in range(iterations):
new_points = []
for i in range(len(points) - 1):
p1, p2 = points[i], points[i + 1]
midpoint = (p1 + p2) / 2
rotated_vector = np.dot(direction, p2 - midpoint)
new_point = midpoint + rotated_vector
new_points.extend([p1, new_point])
new_points.append(points[-1])
points = np.array(new_points)
return points
def plot_dragon_curve(iterations):
points = dragon_curve(iterations)
plt.figure(figsize=(6, 6))
plt.plot(points[:, 0], points[:, 1], color='blue', linewidth=0.7)
plt.axis('equal')
plt.title("Dragon Curve Pattern")
plt.show()
plot_dragon_curve(12)
#source code --> clcoding.com
Code Explanation:
1. Importing Required Libraries
import numpy as np
import matplotlib.pyplot as plt
numpy: A library used for numerical computing. It
helps handle arrays efficiently.
matplotlib.pyplot: A library for plotting graphs and
visualizing the generated fractal pattern.
This function generates the Dragon Curve points
based on the given number of iterations.
Each iteration refines the shape, making it more
complex.
points =
np.array([[0, 0], [1, 0]])
points: This initializes the Dragon Curve with a
straight-line segment between two points:
(0,0) → starting point
(1,0) → ending point
direction: This is a rotation matrix that rotates a
point 90 degrees counterclockwise.
for _ in range(iterations):
This loop runs for the given number of iterations.
new_points: This will store the new set of points
after each iteration.
for i
in range(len(points) - 1):
This loop goes through all adjacent points in the
current list.
p1, p2 = points[i], points[i + 1]
p1: The starting point of the segment.
Finds the midpoint of the segment between p1 and p2.
rotated_vector = np.dot(direction, p2 - midpoint)
p2 - midpoint: Finds the vector from the midpoint to
p2.
new_point = midpoint + rotated_vector
Finds the new rotated point that will be inserted
into the shape.
Adds the old point p1 and the new rotated point to
the list.
new_points.append(points[-1])
Ensures that the last point of the previous
iteration remains in the shape.
Updates points with the new set of points after this
iteration.
return
points
After all iterations, the function returns the final
set of points forming the fractal.
def plot_dragon_curve(iterations):
This function is responsible for visualizing the
generated fractal.
Calls dragon_curve(iterations) to generate the
points.
Creates a new figure with a 6x6 inch size.
Plots the points using:
Y-coordinates (points[:, 1])
Blue color
Ensures that the aspect ratio is equal, so the
pattern does not look stretched.
Adds a title to the plot.
Displays the final fractal plot
0 Comments:
Post a Comment