Branchwell

Watch Encyclopedia / website / exp / double-pendulum.js

1WE.mount('double-pendulum', function (S) {
2 var C = S.C, ctx = S.ctx, P = [], g = 9.81, grab = false;
3 var diff = S.select('Second pendulum starts off by', [['0.001', 'a thousandth of a degree'], ['0.1', 'a tenth of a degree'], ['2', '2 degrees']], '0.1', function () { reset(); });
4 S.button('Start again', function () { reset(); });
5 function reset(a1, a2) { a1 = a1 === undefined ? 2.2 : a1; a2 = a2 === undefined ? 2.6 : a2; var d = +diff.v * Math.PI / 180; P = [{ a: a1, b: a2, wa: 0, wb: 0, tr: [], c: C.acc }, { a: a1 + d, b: a2, wa: 0, wb: 0, tr: [], c: C.blue }]; } reset();
6 function acc(p) { var d = p.a - p.b, den = 3 - Math.cos(2 * d); return [(-3 * g * Math.sin(p.a) - g * Math.sin(p.a - 2 * p.b) - 2 * Math.sin(d) * (p.wb * p.wb + p.wa * p.wa * Math.cos(d))) / den, (2 * Math.sin(d) * (2 * p.wa * p.wa + 2 * g * Math.cos(p.a) + p.wb * p.wb * Math.cos(d))) / den]; }
7 S.pointer({ down: function (x, y) { grab = true; set(x, y); }, move: function (x, y, d) { if (d && grab) set(x, y); }, up: function () { grab = false; } });
8 function set(x, y) { var a = Math.atan2(x - S.W / 2, y - S.H * .4); reset(a, a + .4); }
9 S.loop(function (dt, t) {
10 var w = S.W, h = S.H, L = Math.min(w, h) * .21, ox = w / 2, oy = h * .4;
11 if (!grab) P.forEach(function (p) { for (var i = 0; i < 24; i++) { var st = dt * 1.6 / 24, k = acc(p); p.wa += k[0] * st / 1; p.wb += k[1] * st / 1; p.a += p.wa * st; p.b += p.wb * st; } });
12 S.clear();
13 P.forEach(function (p) { var x1 = ox + L * Math.sin(p.a), y1 = oy + L * Math.cos(p.a), x2 = x1 + L * Math.sin(p.b), y2 = y1 + L * Math.cos(p.b); if (!grab) p.tr.push([x2, y2]); if (p.tr.length > 420) p.tr.shift();
14 for (var i = 1; i < p.tr.length; i++) { ctx.globalAlpha = i / p.tr.length * .8; S.ln(p.tr[i - 1][0], p.tr[i - 1][1], p.tr[i][0], p.tr[i][1], p.c, 1.5); } ctx.globalAlpha = 1;
15 S.ln(ox, oy, x1, y1, C.ink, 2); S.ln(x1, y1, x2, y2, C.ink, 2); S.dot(x1, y1, 7, p.c); S.dot(x2, y2, 9, p.c); });
16 S.dot(ox, oy, 5, C.mut);
17 var sep = Math.abs(P[0].b - P[1].b) + Math.abs(P[0].a - P[1].a);
18 S.say((sep < .05 ? 'Two pendulums, gold and blue, start almost exactly together. Watch closely.' : sep < 1.5 ? 'They are <b>starting to drift apart</b>.' : 'Now they are doing <b>completely different things</b>.') + ' Nothing here is random. The rules are exact, yet a tiny difference at the start grows until the future cannot be predicted. This is chaos. Drag to set a new start.');
19 });
20});