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