/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / compositions / c04-crash / fall.ts
57 lines · 2.5 KBBlameHistoryRaw
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;
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])];
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;
28/**
29 * Nudge whose bob moves `thr` sideways at sim time T. Tipping time is not monotonic in the nudge:
30 * it levels off (even rises a little) at a floor of a few seconds, then drops abruptly once the
31 * nudge itself is nearly visible. So scan a log grid, refine by bisection inside every interval
32 * that brackets T, and take whatever lands closest to T. Nudges below ~1e-15
33 * are lost to rounding.
34 */
35export function nudgeForTip(cfg: PendulumConfig, ratio: number, T: number, thr: number): { nudge: number; tipsAt: number } {
36 const maxT = 3 * T + 10;
37 const tip = (d: number) => tipTime(cfg, d, ratio, thr, maxT);
38 const grid: { d: number; t: number }[] = [];
39 for (let e = -15; e <= -0.5; e += 0.25) grid.push({ d: 10 ** e, t: tip(10 ** e) });
40 // refine every bracket (tip(a) > T ≥ tip(b)); keep whatever lands closest to T
41 const cands = [...grid];
42 for (let i = 0; i + 1 < grid.length; i++) {
43 let a = grid[i], b = grid[i + 1];
44 if (!(a.t > T && b.t <= T)) continue;
45 for (let k = 0; k < 14; k++) {
46 const d = Math.sqrt(a.d * b.d), t = tip(d);
47 if (t > T) a = { d, t };
48 else b = { d, t };
49 }
50 cands.push(a, b);
51 }
52 // closest to T; among near-ties (within 1%), the smallest nudge
53 const err = (c: { t: number }) => Math.abs(c.t - T);
54 const bestErr = Math.min(...cands.map(err));
55 const best = cands.filter((c) => err(c) <= bestErr + 0.01 * T).reduce((x, y) => (y.d < x.d ? y : x));
56 return { nudge: best.d, tipsAt: best.t };
↑↓ move↵openescclose