Title: Draw butterfly curves with different periods in Python
My post Draw a butterfly curve in Python uses the following equations to draw a butterfly curve.
This equation repeats after t varies from 0 to 24 π because 24 π is the smallest value that makes t, 4t, and t/12 all be multiples of 2 π so cos(t), cos(4t), and cos(t/12) all start repeating. That means the curve is not a fractal, but it does have some fractal-like characteristics. For example, it uses relatively simple equations to draw a complex shape. It also draws several curves that are approximately self-similar, although they repeat after t exceeds 24 π.
The earlier example program makes t vary from 0 to 24 π to draw the whole curve, but I wanted to see how much of the curve was drawn when t covered smaller ranges. This program lets you enter the multiple of π that the program should use as the upper bound for t.
Drawing the Curve
This is a very small change to the previous program. Here's the draw_curve method with the changes highlighted in blue.
When the program starts, it initializes tkinter, creates a Canvas widget, and then calls the following method to draw the curve.
def draw_curve(self):
'''Draw the butterfly curve.'''
# Generate the points.
period = float(self.period_var.get())
num_points = 5000
dt = period * math.pi / num_points
points = [get_point(i * dt) for i in range(num_points)]
# Transform to fit the canvas.
self.canvas.update()
wid = self.canvas.winfo_width()
hgt = self.canvas.winfo_height()
margin = 5
target_rect = (margin, margin, wid - margin, hgt - margin)
points = transform_points(points, target_rect)
# Draw.
self.canvas.delete(tk.ALL)
self.canvas.create_line(points, fill='red')
Now the program gets the period from the variable self.period_var attached to the Edit widget, and most of the rest of the method is the same as before. It uses a list comprehension to generate the points and then draws them. The only other difference is that the new version clears the Canvas widget before drawing the points.
Conclusion
Download the example and give it a try. It's not super obvious exactly how different periods affect the curve. The value 1 draws half a butterfly and 2 draws a full butterfly. The result looks symmetric, but it's slightly off. When you use a period of 4, you can see how things don't quite match horizontally. You can also see that with other multiples of 2.
Experiment with the program and look at its code and the previous post for details.
|