Web Analytics
Waves in p5.js – sine in space and time

Waves in p5.js – sine in space and time

The eighth lesson of the guide Program a physics simulation. This time we do not calculate step by step: the wave is given by a formula that gives the displacement of every particle at every moment. Change the wavelength with the arrow keys (← →) and the frequency (↑ ↓), and the key S adds a wave travelling the other way – a standing wave appears (click the canvas first).

Physics: waves and sound – wavelength, frequency, speed v = λ · f, superposition, standing waves.

Programming: a function of two variables (place and time), a loop over the particles, real time (deltaTime), keys.

You should know: lesson 1; preferably the circular motion animation (sine in code).

Step 1: one particle – sine in time

A particle in simple harmonic motion has displacement y = A · sin(ω · t), where ω = 2π · f is the angular frequency. In p5.js we measure time with deltaTime – the number of milliseconds since the previous frame – so the animation runs at real speed whatever the speed of the computer:

t = t + deltaTime / 1000;          // real time since the previous frame, s
const w = TWO_PI * f;              // angular frequency

Step 2: many particles – sine in space

In a wave every particle oscillates in the same way, but lags behind its neighbour: the particle at x does what the first particle did a little earlier. This is written as y = A · sin(k · x − ω · t), where k = 2π / λ. The loop goes through the particles every 10 pixels:

const k = TWO_PI / lambda;         // wave number
for (let x = 0; x <= width; x += 10) {
  let y = A * sin(k * x - w * t);              // a wave travelling to the right
  circle(x, y0 - y, 8);
}

The red particle (x = 80) shows something important: the particles move only up and down, while the wave moves to the right. A wave carries energy, not matter.

Step 3: the speed of the wave

In one period T = 1 / f the wave travels one wavelength, so its speed is v = λ · f. For λ = 160 pixels and f = 0.5 Hz that is 80 pixels per second – the program prints it. Change the frequency with the arrow keys: the crest moves faster, while the wavelength stays the same. (In a real medium it is the other way round: the speed depends on the medium, so a higher frequency means a shorter wavelength – task 1.)

Step 4: two waves – a standing wave

When two waves meet, their displacements add up (superposition). If we add the same wave travelling to the left, sin(kx − ωt) + sin(kx + ωt) = 2 · sin(kx) · cos(ωt): some particles never move (nodes, every λ / 2), and between them they oscillate most strongly (antinodes). This is how a guitar string vibrates.

if (standing) {
  y = y + A * sin(k * x + w * t);            // and a wave travelling to the left
}

Whole program

Copy it into the p5.js editor and delete the line canvas.parent('lesson-canvas');.

// Waves – program from the lesson “Program a physics simulation” (simulacije.svetprogramiranja.com)
const A = 40;            // amplitude, pixels
let lambda = 160;        // wavelength, pixels
let f = 0.5;             // frequency, Hz
let standing = false;    // whether we also add a wave travelling the other way
let t = 0;               // time, s

function setup() {
  const canvas = createCanvas(320, 260);
  canvas.parent('lesson-canvas');
}

function draw() {
  background(248, 250, 252);
  t = t + deltaTime / 1000;          // real time since the previous frame, s

  const k = TWO_PI / lambda;         // wave number
  const w = TWO_PI * f;              // angular frequency
  const y0 = 140;                    // equilibrium position of the particles

  stroke(203, 213, 225);
  strokeWeight(1);
  line(0, y0, width, y0);

  // particles every 10 pixels: each one only moves up and down
  noStroke();
  for (let x = 0; x <= width; x += 10) {
    let y = A * sin(k * x - w * t);              // a wave travelling to the right
    if (standing) {
      y = y + A * sin(k * x + w * t);            // and a wave travelling to the left
    }
    if (x === 80) {
      fill(220, 38, 38);                         // one particle is red
    } else {
      fill(59, 130, 246);
    }
    circle(x, y0 - y, x === 80 ? 12 : 8);
  }

  // numbers
  fill(11, 19, 36);
  textSize(13);
  text('λ = ' + lambda + ' px (← →),  f = ' + f.toFixed(1) + ' Hz (↑ ↓)', 10, 20);
  text('v = λ · f = ' + (lambda * f).toFixed(0) + ' px/s', 10, 40);
  text('S – standing wave: ' + (standing ? 'on' : 'off'), 10, 60);
}

function keyPressed() {
  if (key === 's' || key === 'S') { standing = !standing; }
  if (keyCode === UP_ARROW && f < 1.95) { f = f + 0.1; }
  if (keyCode === DOWN_ARROW && f > 0.15) { f = f - 0.1; }
  if (keyCode === RIGHT_ARROW && lambda < 320) { lambda = lambda + 20; }
  if (keyCode === LEFT_ARROW && lambda > 40) { lambda = lambda - 20; }
  if ([UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW].includes(keyCode)) {
    return false;        // the arrow keys do not scroll the page (other keys work as usual)
  }
}

Tasks for you

  1. In a real medium (air, a rope) the speed of a wave is constant. Change the program so that the speed is v = 80 pixels per second and the wavelength is calculated from the frequency. What happens when you increase the frequency?
    Solution

    Instead of the variable lambda changed by the keys, calculate const lambda = v / f; in draw(). At a higher frequency the wavelength is shorter: at f = 1 Hz λ = 80 px, and at f = 2 Hz only 40 px.

  2. Turn on the standing wave at λ = 160 px. How many nodes (particles at rest) do you see on a canvas 320 pixels wide?
    Solution

    The nodes are every λ / 2 = 80 px: at x = 0, 80, 160, 240 and 320 – 5 nodes. Notice that the red particle (x = 80) stands still.

  3. Make a longitudinal wave: let the particles move left and right, not up and down.
    Solution

    Draw the particle at circle(x + y, y0, 8) instead of circle(x, y0 - y, 8), with a smaller amplitude (e.g. A = 8), so that the particles do not overlap. You will see compressions and rarefactions – like in sound.

  4. Let the second wave travel in the same direction, but with a phase difference φ: y = y + A * sin(k * x - w * t + phi). What happens for φ = 0 and for φ = π?
    Solution

    For φ = 0 the waves reinforce each other (amplitude 2A), and for φ = π (PI) they cancel out completely – all the particles are at rest. This is interference.

Next