xxxxxxxxxx
87
// Display parameters
var cnv = {
w: 500,
h: 500
};
var pivot = {
x: cnv.w / 2,
y: cnv.h / 2
};
var fr = 60;
var loops = 60;
// The parameters of the problem
const g = 9.8;
const l = 1;
const m = 1;
const a_i = 0.05;
const w_i = 0;
const dt = 1.0 / fr / loops;
const L = 0.4 * cnv.h;
// The variables of the problem
var t, a;
function setup() {
// put setup code here
createCanvas(cnv.w, cnv.h);
frameRate(fr);
// The initial conditions of the problem
t = 0;
a = [a_i, w_i];
}
function draw() {
for (let i = 0; i < loops; i++) {
background(220);
// text("Scale: " + l + " m is " + L + " px", 5, 15);
text(millis()/1000, 5, 15);
let tht = a[0];
// Convert solutions to Cartesian
x = pivot.x + L * sin(tht);
y = pivot.y + L * cos(tht);
// draw the pendulum
paint(x, y);
// step the solver
a = step(t, a);
t += dt;
}
}
function evolve(t, u) {
let a = u[0];
let w = u[1];
da = w;
dw = -(g / l) * sin(a);
return [da, dw];
}
function step(t, u) {
// Euler method
let u_ = [];
let du = evolve(t, u);
for (let i = 0; i < u.length; i++) {
u_.push(u[i] + dt * du[i]);
}
return u_;
}
function paint(x, y) {
fill(5);
ellipse(pivot.x, pivot.y, 6, 6);
stroke(20);
line(pivot.x, pivot.y, x, y);
fill(80);
ellipse(x, y, 20);
}