Thursday 7 May 2009

Sine in action part 1

Posting the final draft is proving a little problematic, so I will be splitting it into several sections.

Chunk 54 – Sine in action

In this section we are going to develop a program that uses the sine function. Our program is designed in a modular way, with fairly self contained functions each handling different aspects of the program operation. Where functions could be reused elsewhere they are kept independent of the rest of the program by using arguments passed from other functions instead of relying on global variables.

Although this approach leads to some additional complexity, it is designed to allow code reuse and make future alterations simpler.

We will begin by discussing the individual functions that make up our program. At the end of this section we will combine these to give our main program. The full code is listed at the end; although where it clarifies explanations small excerpts have been used in the discussion.

The sine function

As we saw in section 53 the sine function is a trigonometric function which generates a periodic repeating wave.

The basic function takes the form

f(θ) = amplitude * sin( frequency * θ)

The maximum value of the sine function
f(θ) is equal to the amplitude, and the minimum value is equal to minus the amplitude. The function f(θ) varies smoothly between these values during the period of the wave.

The frequency affects the number of repetitions of the wave within the period 2 π radians; such that if frequency = 1 then the wave repeats once over the period and if
frequency = n then the wave repeats n times.

A damping variable can be used to decrease the amplitude over time such that the maximum and minimum values of the sine function tend towards to zero.

In the following example, the amplitude is decreased with each point plotted by multiplying the amplitude by the variable damping. The angle theta is increased from 0 to TWO_PI as x increases from 0 to width. To do this we define theta as a function of and width. We initialise theta to 0 and then with each iteration we add dTheta, where

dTheta = TWO_PI/width;

Additionally the variable frequency is set to 4 so the wave repeats four times within the period. This is shown in Figure 1.

size(600, 300);
background(0);
stroke(255);
strokeWeight(5);

float y = 0;
float theta = 0.0;
float amplitude = height/2 ;
float damping = 0.994;
float dTheta= TWO_PI/width;
float position = height/2;
float frequency = 4;
smooth();

for(int x=0; x <>
y = position + amplitude*sin(frequency*theta);
point (x, y);
amplitude *= damping;
theta += dTheta;
}













Figure 1 Sine function with damping

No comments: