Title: Draw a kochawave fractal curve with Python
The kochawave fractal is a fairly simple variation of the Koch curve, which is described in the earlier post Draw a Koch fractal curve with Python. Like the Koch curve, it recursively divides an initializer segment into three sections, draws the first and last normally, and replaces the middle section with a side-trip consisting of two segments. In contrast to the Koch curve, where the middle segments are symmetric, the middle part of the kochawave curve is not. To draw the middle section, the curve turns left 30°, draws a segment, turns right 150°, and draws another segment.
The following picture shows a depth 1 kochawave curve. The segments in the middle section are skewed to the right so the yellow triangle is equilateral.
This example uses the following draw_kochawave method to create the curve.
def draw_kochawave(points, depth, p1, theta, length):
'''
Recursively draw a snowflake edge starting at p1 in direction theta
and distance dist. Return the endpoint.
'''
if depth == 0:
# Just move there.
p2 = (p1[0] + length * math.cos(theta),
p1[1] + length * math.sin(theta))
points.append(p2)
return p2
# Recursively draw the edge.
length /= 3
p1 = draw_kochawave(points, depth - 1, p1, theta, length)
theta -= math.radians(30)
l = length * math.sqrt(3)
p1 = draw_kochawave(points, depth - 1, p1, theta, l)
theta += math.radians(150)
p1 = draw_kochawave(points, depth - 1, p1, theta, length)
theta -= math.radians(120)
p1 = draw_kochawave(points, depth - 1, p1, theta, length)
return p1 # Return the final end point.
This is very similar to the method used by the earlier post to draw Koch curves.
If the depth of recursion is 0, the code simply draws a segment of the desired length in the desired direction.
If the depth is greater than 0, the code divides the length by 3 and draws a segment of that length in the desired direction. Next, it turns -30° and draws a segment with the length needed to fit the geometry shown in the picture. The method turns 150° and draws another segment. It turns a final 120° and draws its final segment.
The result is a sort of wave-like shape that reminds me a bit of Under the Wave off Kanagawa (aka The Great Wave) by Katsushika Hokusai.
Download the example to see additional details.
|