Artful Computing

Pattern 2: Increment on the previous iteration

This has been used a number of times in the example programs. In each case we wanted to over a curve, sometimes drawing a line along the curve. In each case it was convenient to break the curve into a number of steps sufficiently large that in the final image they looked smooth. Furthermore, in each case at each step it was convenient to calculate where the current point of the curve should be placed, and then draw a line to this point from where we were at the previous step. The following program fragment traces a sine curve (note angles in radians) ,

float theta;       // The starting value of the angle (assumed to be in Radians)
float dth = 0.1; // Angle increments by this amount each step

float y; // This will hold sin(theta)


float theta_p; // This will hold the angle on the previous iteration step.
float yp; // This will hold sin(theta_p)

yp = 0.0; // We have to set up the values for the "previous" step before
theta_p = 0.0; // the first iteration of the loop.

while(theta < TWO_PI)
{
theta = theta + dth; // The new value of the angle increments the previous value.

y = sin(theta) // The new value of the sine.
line( theta_p, yp, theta,y); // Draw a line from the point defining the curve at the previous step.

theta_p = theta; // The current theta becomes the "previous" theta for the next time round the loop.
yp = y; // The current y becomes the "previous" y for the next time round the loop.
}

Breadcrumbs