f7d91baAdd composition 4: crashJeremy Magland 1// Starting from straight up: the nudge that makes the pendulum visibly tip 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/** Inverted (both arms up), at rest, nudged by d (outer arm by d·ratio) toward `side` (±1). */
7export function inverted(cfg: PendulumConfig, d: number, ratio: number, side: number): DoublePendulum {
8 const p = new DoublePendulum(cfg);
9 p.controlled = false;
10 p.y[0] = Math.PI + side * d;
11 p.y[1] = Math.PI + side * d * ratio;
12 return p;
13}
15export function bob(cfg: PendulumConfig, y: ArrayLike<number>): [number, number] {
16 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])];
17}
19function tipTime(cfg: PendulumConfig, d: number, ratio: number, thr: number, maxT: number): number {
20 const p = inverted(cfg, d, ratio, 1);
21 for (let t = 0; t < maxT; t += DT) {
22 p.step(DT);
23 if (Math.abs(bob(cfg, p.y)[0]) > thr) return t + DT;
24 }
25 return Infinity;
26}
28/**
29 * Nudge whose bob moves `thr` sideways at sim time T (bisection on log d). Straight up is
30 * unstable, so the time to tip grows only like log(1/d); nudges below ~1e-15 are lost to rounding.
31 */
32export function nudgeForTip(cfg: PendulumConfig, ratio: number, T: number, thr: number): { nudge: number; tipsAt: number } {
33 const maxT = 3 * T + 10;
34 let lo = 1e-15, hi = 0.3;
35 if (tipTime(cfg, lo, ratio, thr, maxT) <= T) return { nudge: lo, tipsAt: tipTime(cfg, lo, ratio, thr, maxT) };
36 if (tipTime(cfg, hi, ratio, thr, maxT) >= T) return { nudge: hi, tipsAt: tipTime(cfg, hi, ratio, thr, maxT) };
37 for (let i = 0; i < 18; i++) {
38 const mid = Math.sqrt(lo * hi);
39 if (tipTime(cfg, mid, ratio, thr, maxT) > T) lo = mid;
40 else hi = mid;
41 }
42 const nudge = Math.sqrt(lo * hi);
43 return { nudge, tipsAt: tipTime(cfg, nudge, ratio, thr, maxT) };
44}