/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / compositions / c03-divergence / release.ts
53 lines · 2.4 KBCodeBlameHistory
bc546ddAdd composition 3: divergenceJeremy Magland 1// Release states and the offset that makes the pendulums separate at a chosen time.
2import { DoublePendulum, type PendulumConfig } from "../../physics/doublePendulum.ts";
4export const DT = 0.002; // simulation step (sim seconds), shared with the piece
6/** Released from rest at angles (θ1, θ2), with the outer arm offset by `d`. */
7export function released(cfg: PendulumConfig, th1: number, th2: number, d: number): DoublePendulum {
8 const p = new DoublePendulum(cfg);
9 p.controlled = false;
10 p.y[0] = th1;
11 p.y[1] = th2 + d;
12 p.y[2] = 0;
13 p.y[3] = 0;
14 return p;
17/** Bottom-bob position. */
18export function bob(cfg: PendulumConfig, y: ArrayLike<number>): [number, number] {
19 return [cfg.l1 * Math.sin(y[0]) + cfg.l2 * Math.sin(y[1]), cfg.l1 * Math.cos(y[0]) + cfg.l2 * Math.cos(y[1])];
22/** Sim time at which two pendulums offset by ±d/2 first have their bobs `thr` apart (Infinity if not by maxT). */
23function separationTime(cfg: PendulumConfig, th1: number, th2: number, d: number, thr: number, maxT: number): number {
24 const a = released(cfg, th1, th2, -d / 2);
25 const b = released(cfg, th1, th2, d / 2);
26 for (let t = 0; t < maxT; t += DT) {
27 a.step(DT);
28 b.step(DT);
29 const [ax, ay] = bob(cfg, a.y), [bx, by] = bob(cfg, b.y);
30 if (Math.hypot(ax - bx, ay - by) > thr) return t + DT;
31 }
32 return Infinity;
35/**
36 * Total offset (between the two outermost pendulums) whose bobs separate by `thr` at sim time
37 * `T`, found by bisection on log(offset). Separation in a chaotic system depends on the exact
38 * state, so this is calibrated for each release. Offsets below ~1e-15 rad are lost to rounding,
39 * which bounds how late separation can be.
40 */
41export function offsetForSeparation(cfg: PendulumConfig, th1: number, th2: number, T: number, thr: number): { offset: number; separatesAt: number } {
42 const maxT = 3 * T + 10;
43 let lo = 1e-15, hi = 1e-2; // separation happens late at lo, early at hi
44 if (separationTime(cfg, th1, th2, lo, thr, maxT) <= T) return { offset: lo, separatesAt: separationTime(cfg, th1, th2, lo, thr, maxT) };
45 if (separationTime(cfg, th1, th2, hi, thr, maxT) >= T) return { offset: hi, separatesAt: separationTime(cfg, th1, th2, hi, thr, maxT) };
46 for (let i = 0; i < 16; i++) {
47 const mid = Math.sqrt(lo * hi);
48 if (separationTime(cfg, th1, th2, mid, thr, maxT) > T) lo = mid;
49 else hi = mid;
50 }
51 const offset = Math.sqrt(lo * hi);
52 return { offset, separatesAt: separationTime(cfg, th1, th2, offset, thr, maxT) };
↑↓ move↵openescclose