The fourth lesson of the guide Program a physics simulation. A mass on a spring oscillates up and down, and the total energy should stay the same. Here we run two simulations of the same mass at the same time, which differ in only two lines of code – in the order of the calculation. Watch what happens to the left mass after about ten seconds (click the canvas to start again).
Physics: mass and spring – spring force F = −k · x, simple harmonic motion, T = 2π · √(m / k), energy.
Programming: accuracy of a numerical method, plain Euler and Euler–Cromer, checking the energy, constrain().
You should know: lessons 1–3.
A spring pulls with a force proportional to the stretch and directed towards the equilibrium position: F = −k · x (Hooke's law). So the acceleration of the mass is a = −(k / m) · x. For a vertical spring, gravity only moves the equilibrium position down; if we measure x from the equilibrium position, gravity no longer appears in the equation.
const m = 0.5; // mass, kg
const k = 8; // spring constant, N/m
const A = 0.08; // initial stretch, m
// ...
const a2 = -k / m * cromer.x;
The period of oscillation is T = 2π · √(m / k) = 2π · √(0.5 / 8) ≈ 1.571 s.
In Euler's method we calculate the new velocity and the new position. But in which order? Plain Euler calculates the new position from the old velocity, while Euler–Cromer first calculates the new velocity and then the new position from the new velocity:
// plain Euler: new position from the OLD velocity
const a1 = -k / m * euler.x;
euler.x = euler.x + euler.v * dt;
euler.v = euler.v + a1 * dt;
// Euler–Cromer: first the new velocity, then the new position from the NEW velocity
const a2 = -k / m * cromer.x;
cromer.v = cromer.v + a2 * dt;
cromer.x = cromer.x + cromer.v * dt;
It looks like an unimportant difference. In the previous lessons (free fall, projectile motion) we used the second way without saying much about it.
The best check of any simulation is conservation of energy. The total energy of a mass on a spring is E = k · x² / 2 + m · v² / 2, and at the start it is 8 · 0.08² / 2 = 25.6 mJ. The program prints it for both masses:
function energy(mass) {
return 0.5 * k * mass.x * mass.x + 0.5 * m * mass.v * mass.v; // J
}
| time | plain Euler | Euler–Cromer |
|---|---|---|
| 1 s | 33.4 mJ | 24.8 mJ |
| 5 s | 96.8 mJ | 25.0 mJ |
| 10 s | 366.3 mJ | 26.5 mJ |
| 20 s | 5240 mJ | 25.5 mJ |
Plain Euler “pumps” energy into the system – the mass oscillates more and more strongly, which is physically impossible. Euler–Cromer keeps the energy around the correct value (it wobbles a little, but does not grow). That is why Euler–Cromer or even better methods (e.g. Runge–Kutta, which the simulations on this site use) are used for oscillations, orbits and similar problems.
We draw the spring as a zigzag line from the ceiling to the mass. The function constrain() keeps the position of the mass on the canvas – otherwise a mass that “goes wild” would disappear off the screen.
const y = constrain(equilibrium + mass.x * SCALE, top + 40, height - 70);
beginShape();
vertex(xc, top);
for (let i = 1; i < 12; i++) {
vertex(xc + (i % 2 === 0 ? -12 : 12), top + (y - 20 - top) * i / 12);
}
vertex(xc, y - 20);
endShape();
Copy it into the p5.js editor and delete the line canvas.parent('lesson-canvas');.
// Mass and spring – program from the lesson “Program a physics simulation” (simulacije.svetprogramiranja.com)
const m = 0.5; // mass, kg
const k = 8; // spring constant, N/m
const A = 0.08; // initial stretch, m
const SCALE = 400; // how many pixels make one metre
const dt = 1 / 60; // time step, s
let euler, cromer; // two masses: plain Euler and Euler–Cromer
let t;
function setup() {
const canvas = createCanvas(320, 380);
canvas.parent('lesson-canvas');
start();
}
function start() {
euler = { x: A, v: 0 }; // x – stretch from the equilibrium position (downwards), m
cromer = { x: A, v: 0 };
t = 0;
}
function energy(mass) {
return 0.5 * k * mass.x * mass.x + 0.5 * m * mass.v * mass.v; // J
}
function draw() {
background(248, 250, 252);
// plain Euler: new position from the OLD velocity
const a1 = -k / m * euler.x;
euler.x = euler.x + euler.v * dt;
euler.v = euler.v + a1 * dt;
// Euler–Cromer: first the new velocity, then the new position from the NEW velocity
const a2 = -k / m * cromer.x;
cromer.v = cromer.v + a2 * dt;
cromer.x = cromer.x + cromer.v * dt;
t = t + dt;
// ceiling
stroke(51, 65, 85);
strokeWeight(4);
line(20, 40, width - 20, 40);
drawSpring(85, euler, 'plain Euler');
drawSpring(235, cromer, 'Euler–Cromer');
noStroke();
fill(11, 19, 36);
textSize(13);
textAlign(LEFT);
text('t = ' + t.toFixed(1) + ' s (click to restart)', 10, height - 8);
}
function drawSpring(xc, mass, label) {
const top = 40;
const equilibrium = 190;
const y = constrain(equilibrium + mass.x * SCALE, top + 40, height - 70);
// spring: a zigzag line from the ceiling to the mass
noFill();
stroke(100, 116, 139);
strokeWeight(2);
beginShape();
vertex(xc, top);
for (let i = 1; i < 12; i++) {
vertex(xc + (i % 2 === 0 ? -12 : 12), top + (y - 20 - top) * i / 12);
}
vertex(xc, y - 20);
endShape();
// mass
noStroke();
fill(249, 115, 22);
rect(xc - 20, y - 20, 40, 40, 4);
// labels
fill(11, 19, 36);
textSize(13);
textAlign(CENTER);
text(label, xc, 22);
text('x = ' + (mass.x * 100).toFixed(1) + ' cm', xc, height - 46);
text('E = ' + (energy(mass) * 1000).toFixed(1) + ' mJ', xc, height - 28);
}
function mousePressed() {
if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
start();
}
}
The mass oscillates faster: T = 2π · √(0.5 / 32) ≈ 0.785 s – half as long, because the period is proportional to √(1 / k).
The simulation (Euler–Cromer) gives 1.571 s – the same as the formula. Plain Euler gives worse and worse results because its amplitude grows.
dt = 1 / 600, 10 steps per frame). What is the energy of the left mass after 10 s?
About 33.4 mJ instead of 366 mJ. A smaller step slows down the “pumping” but does not remove it – so it is better to change the method than only to make the step smaller.
In the line with the acceleration of the right mass write const a2 = -k / m * cromer.x - 0.5 * cromer.v;. The amplitude and the energy decrease: after 10 s the amplitude is only about
0.8 cm. The energy turns into heat.