xxxxxxxxxx
110
// Display parameters
var cnv = {
w: 500,
h: 500
};
var pivot = {
x: cnv.w / 2,
y: cnv.h / 2
};
var fr = 60;
var loops = 10;
// The parameters of the problem
const g = 9.8;
const l = 9.8;
const m = 0.1;
const a_i = 3.14;
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(frameRate().toFixed(1), 5, 15);
// text("Scale: " + l + " m is " + L + " px", 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 add(v1, v2) {
let v = [];
for(let i = 0; i < v1.length; i++) {
v.push(v1[i] + v2[i]);
}
return v;
}
function mul(c, v) {
let v_ = [];
for(let i = 0; i < v.length; i++) {
v_.push(c*v[i]);
}
return v_;
}
function evolve(t, u) {
let a = u[0];
let w = u[1];
let da = w;
let dw = -(g / l) * sin(a);
return [da, dw];
}
function step(t, u) {
// RK4 method
let u_ = [];
let k1 = evolve(t, u);
let k2 = evolve(t + dt/2, add(u, mul(dt/2, k1)));
let k3 = evolve(t + dt/2, add(u, mul(dt/2, k2)));
let k4 = evolve(t + dt, add(u, mul(dt, k3)));
// console.log(evolve(t, u));
for (let i = 0; i < u.length; i++) {
u_.push(u[i] + dt*(k1[i] + 2*k2[i] + 2*k3[i] + k4[i])/6);
}
// console.log(u_);
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);
}