// Starting from straight up: the nudge that makes the pendulum visibly tip at a chosen time. import { cos, pow, sin } from "../../physics/dmath.ts"; 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 * sin(y[0]) + cfg.l2 * sin(y[1]), cfg.l1 * cos(y[0]) + cfg.l2 * 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. Tipping time is not monotonic in the nudge: * it levels off (even rises a little) at a floor of a few seconds, then drops abruptly once the * nudge itself is nearly visible. So scan a log grid, refine by bisection inside every interval * that brackets T, and take whatever lands closest to T. 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; const tip = (d: number) => tipTime(cfg, d, ratio, thr, maxT); const grid: { d: number; t: number }[] = []; for (let i = 0; i <= 58; i++) { const d = pow(10, -15 + 0.25 * i); grid.push({ d, t: tip(d) }); } // refine every bracket (tip(a) > T ≥ tip(b)); keep whatever lands closest to T const cands = [...grid]; for (let i = 0; i + 1 < grid.length; i++) { let a = grid[i], b = grid[i + 1]; if (!(a.t > T && b.t <= T)) continue; for (let k = 0; k < 14; k++) { const d = Math.sqrt(a.d * b.d), t = tip(d); if (t > T) a = { d, t }; else b = { d, t }; } cands.push(a, b); } // closest to T; among near-ties (within 1%), the smallest nudge const err = (c: { t: number }) => Math.abs(c.t - T); const bestErr = Math.min(...cands.map(err)); const best = cands.filter((c) => err(c) <= bestErr + 0.01 * T).reduce((x, y) => (y.d < x.d ? y : x)); return { nudge: best.d, tipsAt: best.t }; }