sine and cosine

(Co)sine functions are very useful in programming, but you need to know when to use them. The most important thing to remember is that these are periodic functions. This means that they don't just increase or decrease, but sometimes increase and sometimes decrease, always smoothly.

Let's start with the most basic forms:

and

Some points to notice:

Just like with the previous functions, we can add a scale coefficient or a constant term offset.

A coefficient outside of the (co)sine function will scale the range:

A coefficient inside the (co)sine function will scale the period:

A constant term outside the (co)sine function results in a vertical offset:

A constant term inside the (co)sine function results in a horizontal offset:

These functions come in really handy for animation. For example, let's simulate a ball bouncing on the floor.

The ball starts in the air, so we will use a cosine function:

Assuming our window is 300 pixels high, we'll scale the range so that we cover as much space as possible:

We also want to account for the radius of the ball, so the minimum value needs to be slightly greater than 0:

If we plot this in Grapher, we'll see that the period is way too small, so let's fix that:

Since our ball never goes underground (below 0), we'll use the absolute value operation to make all our values positive:

Finally, we want the ball to bounce less and less over time, so we'll add an x coefficient to scale the whole thing. We use x + 160 instead of x so that we don't divide by 0 on the first frame.

//----------------------------
// variables
float currY;
int currTime;

//---------------------------- 
void setup() {
  // set up the applet
  size(300, 300);
  smooth();
  frameRate(30);

  // reset the animation independent variable (time)
  currTime = 0;  

  // set the ball color
  noStroke();
  fill(#FF6F00);
}

//----------------------------
void draw() {
  // clear the screen
  background(0);

  // move the ball
  currY = height - move(currTime);

  // draw the ball  
  ellipse(width/2, currY, 20, 20);

  currTime++;
}

//----------------------------
void mousePressed() {
  // reset the animation independent variable (time)
  currTime = 0;  
}

//----------------------------
float move(float x) {
  return 280 * (abs(cos(x / 10.0f)) / (0.006f * (x + 160))) + 10;
}		

Math For Artists Who Now Need to Program

Elie Zananiri
ITP DriveBy
1 Oct 2008