#!/usr/bin/env node
// Buffon's Needle + the Lazzarini scandal — verifier.
//
// Two things are checked here, both shown on the page:
//   A. The honest method works: dropping a short needle (L <= d) across ruled
//      lines crosses one with probability p = 2L/(pi d). So pihat = 2 L N / (d H)
//      converges to pi, with a 1/sqrt(N) error envelope we measure empirically
//      and compare to the delta-method standard error.
//   B. Lazzarini's 1901 result is too good to be true. With his exact setup
//      (L/d = 5/6, N = 3408), we recompute:
//        - that his reported 1808 hits give pihat = 5680/1808 = 355/113 EXACTLY;
//        - the 1-sigma error of the method for that setup (~0.05);
//        - that 355/113 requires H to equal one single integer (1808); the
//          neighbours H = 1807, 1809 miss pi in the third decimal;
//        - by Monte-Carlo, the fraction of honest 3408-throw experiments that
//          land within Lazzarini's claimed precision of pi (essentially none).
//
// Sources (checked, see the page's apparatus):
//   Buffon, G.-L. Leclerc (1777). Posed 1733; published in the "Essai
//     d'arithmetique morale".  p = 2L/(pi d) for L <= d.
//   Lazzarini, M. (1901). 3408 throws, L/d = 5/6, reported pi ~ 3.1415929.
//   Badger, L. (1994). "Lazzarini's Lucky Approximation of pi."
//     Mathematics Magazine 67(2), 83-91 — the definitive statistical debunk.
//   355/113 = Zu Chongzhi's Milu (5th c.), the best rational approximation of
//     pi with numerator/denominator under five digits; |355/113 - pi| ~ 2.67e-7.
//
// Deterministic: a small seeded PRNG, so every number below reproduces exactly.
// Run: node research/buffon-needle/verify.mjs

'use strict';

const PI = Math.PI;
let pass = 0, fail = 0;
const log = [];
function check(name, got, want, tol) {
  const ok = (tol === undefined) ? (got === want) : (Math.abs(got - want) <= tol);
  (ok ? pass++ : fail++);
  log.push(`${ok ? 'ok  ' : 'FAIL'}  ${name}: got ${got}${tol === undefined ? '' : ` (want ${want} ± ${tol})`}`);
}

// ---- deterministic PRNG (mulberry32) ----
function mulberry32(seed) {
  let a = seed >>> 0;
  return function () {
    a |= 0; a = (a + 0x6D2B79F5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

// ---- one Buffon experiment: N throws, short needle length L, line spacing d ----
// Short-needle model (L <= d): nearest-line distance u ~ U(0, d/2),
// acute angle to lines th ~ U(0, pi/2). Crosses iff (L/2) sin(th) >= u.
function buffonHits(N, L, d, rng) {
  let hits = 0;
  const half = d / 2, hl = L / 2;
  for (let i = 0; i < N; i++) {
    const u = rng() * half;
    const th = rng() * (PI / 2);
    if (hl * Math.sin(th) >= u) hits++;
  }
  return hits;
}
const piHat = (N, L, d, H) => (2 * L * N) / (d * H);

// =====================================================================
// A. The honest method converges to pi with the predicted error envelope
// =====================================================================
{
  const L = 1, d = 1;                 // needle as long as the gap (max sensitivity)
  const p = 2 * L / (PI * d);
  check('crossing probability p = 2L/(pi d)', p, 0.6366197723675814, 1e-15);

  // A big honest run reproduces pi to ~2 decimals.
  const rng = mulberry32(20260626);
  const N = 4_000_000;
  const H = buffonHits(N, L, d, rng);
  const est = piHat(N, L, d, H);
  log.push(`    honest run: ${N.toLocaleString('en-US')} throws, ${H.toLocaleString('en-US')} hits -> pihat = ${est.toFixed(6)}`);
  check('4M-throw estimate is near pi', est, PI, 0.01);

  // The error of pihat scales like 1/sqrt(N): SE = sqrt(pi^2 (pi - 2L/d) / (2 L N / d)).
  // Equivalent delta-method form below; we confirm the 1/sqrt(N) law by running
  // many independent batches at two sizes and checking the RMS error halves
  // when N quadruples.
  function rmsError(N, batches, rng) {
    let s2 = 0;
    for (let b = 0; b < batches; b++) {
      const H = buffonHits(N, L, d, rng);
      const e = piHat(N, L, d, H) - PI;
      s2 += e * e;
    }
    return Math.sqrt(s2 / batches);
  }
  const rng2 = mulberry32(7);
  const rms1 = rmsError(2500, 400, rng2);
  const rms4 = rmsError(10000, 400, rng2);
  const ratio = rms1 / rms4;        // expect ~2 (sqrt of the 4x)
  log.push(`    RMS error at N=2500: ${rms1.toFixed(4)};  at N=10000: ${rms4.toFixed(4)};  ratio ${ratio.toFixed(3)} (expect ~2)`);
  check('error follows 1/sqrt(N) (quadruple N -> halve error)', ratio, 2.0, 0.35);
}

// =====================================================================
// B. Lazzarini's setup, recomputed
// =====================================================================
const Ld = 5 / 6;                    // his needle-to-spacing ratio
const N_L = 3408;                    // his throw count
const H_L = 1808;                    // his reported hits
const p_L = 2 * Ld / PI;             // = 5/(3 pi)
check("Lazzarini crossing prob p = 5/(3 pi)", p_L, 5 / (3 * PI), 1e-15);
log.push(`    Lazzarini p = ${p_L.toFixed(6)};  expected hits N*p = ${(N_L * p_L).toFixed(4)}`);

// B0. The engineered N: his EXPECTED hit count is 1808 almost exactly, and
// 5680/1808 = 355/113. He didn't pick 3408 at random — he picked the N whose
// mean outcome lands on the celebrated Milu. (round(N*p) = 1808.)
check('expected hits N*p rounds to 1808 (the target integer)', Math.round(N_L * p_L), 1808);
check('expected hits N*p is within 0.01 of 1808 (designed, not lucky)', N_L * p_L, 1808, 0.01);

// B1. His reported hits give 355/113 EXACTLY (integer arithmetic, no rounding).
// pihat = 2*(5/6)*3408 / 1808 = (5*3408)/(3*1808) = 17040/5424.  Reduce:
function gcd(a, b) { return b ? gcd(b, a % b) : a; }
const num = 5 * N_L, den = 3 * H_L;          // 17040 / 5424
const g = gcd(num, den);
check('Lazzarini pihat numerator reduces to 355', num / g, 355);
check('Lazzarini pihat denominator reduces to 113', den / g, 113);
const piHatL = piHat(N_L, Ld, 1, H_L);
check('Lazzarini pihat = 355/113 numerically', piHatL, 355 / 113, 1e-12);
log.push(`    pihat = 17040/5424 = ${num / g}/${den / g} = ${(355 / 113).toFixed(7)}  (pi = ${PI.toFixed(7)})`);
check('|355/113 - pi| ~ 2.67e-7', Math.abs(355 / 113 - PI), 2.667e-7, 1e-9);

// B2. 355/113 is a razor: only H = 1808 yields it; the neighbours miss pi early.
const piLo = piHat(N_L, Ld, 1, H_L + 1);     // one MORE hit
const piHi = piHat(N_L, Ld, 1, H_L - 1);     // one FEWER hit
log.push(`    H=1807 -> ${piHi.toFixed(5)};  H=1808 -> ${piHatL.toFixed(7)};  H=1809 -> ${piLo.toFixed(5)}`);
check('one extra hit (H=1809) already misses pi by >1e-3', Math.abs(piLo - PI) > 1e-3, true);
check('one fewer hit (H=1807) already misses pi by >1e-3', Math.abs(piHi - PI) > 1e-3, true);

// B3. The method's own 1-sigma error for his setup (delta method).
// Var(pihat) ~ (2L/(d N p^2))^2 * N p (1-p) = 4 L^2 (1-p) / (d^2 N p^3).
const seL = Math.sqrt(4 * Ld * Ld * (1 - p_L) / (N_L * p_L ** 3));
log.push(`    method 1-sigma error for his setup: +/- ${seL.toFixed(4)}  (so it resolves ~1 decimal, not 6)`);
check('Lazzarini-setup standard error ~ 0.05', seL, 0.0501, 5e-3);
// His claimed error (2.67e-7) is this many sigmas below what the method delivers:
const ordersBelow = Math.log10(seL / Math.abs(355 / 113 - PI));
log.push(`    his claimed precision is ${ordersBelow.toFixed(1)} orders of magnitude finer than the method's noise`);
check('claimed precision ~5 orders finer than the noise floor', ordersBelow, 5.27, 0.3);

// B3b. Borrowed precision: how many throws would an HONEST run need so that the
// method's 1-sigma error equals Lazzarini's claimed error (2.67e-7)? Since
// SE ~ 1/sqrt(N), N scales as (seL / claimed)^2.
const claimedErr = Math.abs(355 / 113 - PI);
const nNeeded = N_L * (seL / claimedErr) ** 2;
log.push(`    to legitimately resolve pi to his claimed precision the method needs ~${nNeeded.toExponential(1)} throws`);
log.push(`      (vs his 3408) -- about ${(nNeeded / N_L).toExponential(1)}x more. The 6 digits were borrowed, not measured.`);
check('honest run needs ~1e14 throws for his claimed precision', Math.log10(nNeeded), 14.1, 0.4);

// B4. Monte-Carlo: how often does an HONEST 3408-throw experiment land as close
// to pi as Lazzarini claimed? Simulate many and count.
{
  const rng = mulberry32(48879); // fixed seed (0xBEEF)
  const TRIALS = 200000;
  const tol = Math.abs(355 / 113 - PI);   // his claimed closeness, ~2.67e-7
  let within = 0, hit1808 = 0;
  const errs = [];
  for (let t = 0; t < TRIALS; t++) {
    const H = buffonHits(N_L, Ld, 1, rng);
    if (H === H_L) hit1808++;
    const est = piHat(N_L, Ld, 1, H);
    if (Math.abs(est - PI) <= tol) within++;
    if (t < 4000) errs.push(est - PI);
  }
  const empSD = Math.sqrt(errs.reduce((s, e) => s + e * e, 0) / errs.length);
  const fracHit = hit1808 / TRIALS;
  log.push(`    Monte-Carlo: ${TRIALS.toLocaleString('en-US')} honest 3408-throw experiments`);
  log.push(`      empirical SD of pihat = ${empSD.toFixed(4)}  (matches delta method ${seL.toFixed(4)})`);
  log.push(`      rolled exactly H=1808 (the ONLY integer giving 355/113): ${hit1808} = ${(100 * fracHit).toFixed(2)}%`);
  log.push(`      landed within his claimed precision of pi: ${within} = ${(100 * within / TRIALS).toFixed(2)}%  (identical set: 355/113 IS that close)`);
  log.push(`      => not "astronomically rare": ~1 in ${Math.round(1 / fracHit)}. The tell isn't impossibility,`);
  log.push(`         it's reporting 6 digits from a +/-0.05 method, landed on a pre-existing constant.`);
  check('empirical SD matches the analytic standard error', empSD, seL, 0.01);
  // The honest claim: rolling the target integer is ~1.4% — uncommon, not impossible.
  check('P(roll exactly H=1808) is about 1.4% (not astronomically rare)', fracHit, 0.0138, 0.004);
  // And "within his precision" is the SAME event (only 355/113 is that close).
  check('within-precision set == rolled-1808 set', within, hit1808);
}

// =====================================================================
console.log(log.join('\n'));
console.log(`\n${pass}/${pass + fail} checks passed.`);
process.exit(fail ? 1 : 0);
