Visualize sinusoidal waves using Python
Sinusoidal waves are the most basic trigonometric periodic curves, which is also known as the sine curve. Here we will see how sine function is related to a circle. Even though the sine function is a trigonometric function, it has more to do with a circle rather than a triangle.
Consider a simple equation of a circle:
where r is the radius of the circle with center at origin (0,0) as shown in the figure below.
Sine is nothing but the measurement of the y-displacement from the origin as the angle increases as shown in the figure below:
We can visualize this definition of sine using python and the pygame module. Pygame is an open-source python package that is mainly used for creating video games.
- Create a circle with radius r.
- Draw the radius of the circle. The endpoints of the radius will be (0,0) and (r*cos a, r*sin a), where the point (r*cos a, r*sin a) will always be of the circle.
- Draw the sine curve
- Then draw a line that will join the starting point of the sine wave and the endpoint of the radius of the circle. The length is called the gap for sake of simplicity.
Note: Here, the position of radius means the position of the head of the radius of the circle. Abs
Drawing the sine curve
Draw a circle and animate its radius such that the endpoint of the radius will cover all the points on the circumference of the circle. This can be done using an infinite while loop and drawing a line from the center of the circle to (r* cos t,r*sin t). Then declare a list Ys to store all the r*sin t values at the beginning of the list.
This will basically keep a track of all the r*sin t values from the initial position of the radius till its current new position. These values will be used later to show the sine curve. Create a for loop to loop through the elements of Ys and then draw a circle of radius 1 and width 1, with abscissa starting from 0 to len(Ys) and ordinate will be the corresponding Ys values i.e, Ys[i], where index i ∈ [0, len(Ys)-1]. The abscissa needs to be shifted by a certain amount enough to make the animation tidy.
In the animation, the gap is shown by a black line that can be increased or decreased by the user.
Below is the implementation:
Note: Use left and right arrows to decrease or increase the gap between the circle and the sine curve. Use ECS to exit the window or QUIT.