// Starting from straight up: the nudge that makes the pendulum visibly tip at a chosen time. import { DoublePendulum, type PendulumConfig } from "../../physics/doublePendulum.ts"; export const DT = 0.002; // simulation step (sim seconds), shared with the piece /** Inverted (both arms up), at rest, nudged by d (outer arm by d·ratio) toward `side` (±1). */ export function inverted(cfg: PendulumConfig, d: number, ratio: number, side: number): DoublePendulum { const p = new DoublePendulum(cfg); p.controlled = false; p.y[0] = Math.PI + side * d; p.y[1] = Math.PI + side * d * ratio; return p; } export function bob(cfg: PendulumConfig, y: ArrayLike): [number, number] { 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])]; } function tipTime(cfg: PendulumConfig, d: number, ratio: number, thr: number, maxT: number): number { const p = inverted(cfg, d, ratio, 1); for (let t = 0; t < maxT; t += DT) { p.step(DT); if (Math.abs(bob(cfg, p.y)[0]) > thr) return t + DT; } return Infinity; } /** * Nudge whose bob moves `thr` sideways at sim time T (bisection on log d). Straight up is * unstable, so the time to tip grows only like log(1/d); nudges below ~1e-15 are lost to rounding. */ export function nudgeForTip(cfg: PendulumConfig, ratio: number, T: number, thr: number): { nudge: number; tipsAt: number } { const maxT = 3 * T + 10; let lo = 1e-15, hi = 0.3; if (tipTime(cfg, lo, ratio, thr, maxT) <= T) return { nudge: lo, tipsAt: tipTime(cfg, lo, ratio, thr, maxT) }; if (tipTime(cfg, hi, ratio, thr, maxT) >= T) return { nudge: hi, tipsAt: tipTime(cfg, hi, ratio, thr, maxT) }; for (let i = 0; i < 18; i++) { const mid = Math.sqrt(lo * hi); if (tipTime(cfg, mid, ratio, thr, maxT) > T) lo = mid; else hi = mid; } const nudge = Math.sqrt(lo * hi); return { nudge, tipsAt: tipTime(cfg, nudge, ratio, thr, maxT) }; }