#!/usr/bin/env node
// Bertrand's paradox — the "random chord" problem has three classic answers
// (1/3, 1/2, 1/4) depending on how you make a chord "at random", plus a fourth
// physical construction (random line / "throw a straw") that lands on 1/2 and is
// the one invariant under translation + rotation + scaling (Jaynes 1973).
//
// Every probability stated on the page is recomputed here two independent ways:
//   (1) the exact closed form, derived from R√3 = inscribed-equilateral-triangle side;
//   (2) a seeded Monte-Carlo estimate that must land within tolerance.
// The random-radius and ideal random-line laws both make perpendicular distance
// uniform. We compare the straw-drop with the 1/2 limit using growing throwing
// windows and a joint shift of circle and window, keeping the radius fixed.
// No network, no deps; `node research/bertrand-paradox/verify.mjs`.
'use strict';

// ---- deterministic RNG (mulberry32) so the run is reproducible ----------------
function mulberry32(a) {
  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;
  };
}

const R = 1;                       // unit circle
const SIDE = Math.sqrt(3) * R;     // side of inscribed equilateral triangle = R√3
const N = 4_000_000;               // trials per method
const TOL = 0.002;                 // Monte-Carlo tolerance (≈ a few σ at this N)

let pass = 0, fail = 0;
const log = [];
function check(name, got, want, tol = TOL) {
  const ok = Math.abs(got - want) <= tol;
  log.push(`${ok ? 'PASS' : 'FAIL'}  ${name}: got ${got.toFixed(5)}  want ${want.toFixed(5)}  |Δ|=${Math.abs(got - want).toExponential(2)}`);
  ok ? pass++ : fail++;
  return ok;
}

// ---- the geometric fact the whole thing rests on ------------------------------
// A chord at perpendicular distance d from the centre has length 2√(R²−d²).
// It is longer than the triangle side R√3  ⟺  2√(R²−d²) > R√3  ⟺  d < R/2.
{
  const lenAtHalf = 2 * Math.sqrt(R * R - (R / 2) * (R / 2));
  check('triangle side  = R√3', SIDE, Math.sqrt(3), 1e-12);
  check('threshold dist = R/2 gives chord == side', lenAtHalf, SIDE, 1e-12);
}

// ---- Method A: two random endpoints on the circumference  → 1/3 ---------------
// Fix one endpoint; the chord beats the side iff the other endpoint lands on the
// far 1/3 arc. Chord(θ) = 2·sin(Δ/2), Δ the angular gap.
{
  const rnd = mulberry32(0xA11CE);
  let hit = 0;
  for (let i = 0; i < N; i++) {
    const d = 2 * Math.PI * rnd();           // angular separation (one endpoint fixed)
    if (2 * Math.abs(Math.sin(d / 2)) > SIDE) hit++;
  }
  check('A) random endpoints   (exact 1/3)', hit / N, 1 / 3);
}

// ---- Method B: random radius, uniform point along it  → 1/2 -------------------
// Perpendicular distance d ~ Uniform[0,R]; favourable iff d < R/2.
{
  const rnd = mulberry32(0xB2C);
  let hit = 0;
  for (let i = 0; i < N; i++) {
    const d = R * rnd();
    if (d < R / 2) hit++;
  }
  check('B) random radius      (exact 1/2)', hit / N, 1 / 2);
}

// ---- Method C: midpoint uniform over the disk  → 1/4 --------------------------
// Uniform-in-disk via d = R√u; favourable iff d < R/2 ⟺ inner disk area ratio 1/4.
{
  const rnd = mulberry32(0xC0FFEE);
  let hit = 0;
  for (let i = 0; i < N; i++) {
    const d = R * Math.sqrt(rnd());          // correct uniform-in-disk radial law
    if (d < R / 2) hit++;
  }
  check('C) midpoint in disk   (exact 1/4)', hit / N, 1 / 4);
}

// ---- Method D: throw a random straight line ("straw"); condition on crossing --
// The kinematic (translation+rotation invariant) measure on lines makes the
// perpendicular distance p ~ Uniform over [0,R] given the line meets the circle,
// so this must coincide with Method B → 1/2. We simulate it *physically*: drop a
// line of random orientation through a random point in a big window, keep the ones
// that cross the unit circle, and measure the chord. Each throwing window is
// centred on the circle; shifting their common centre leaves relative positions unchanged.
function randomLineMethod(seed, win, cx, cy) {
  const rnd = mulberry32(seed);
  let hit = 0, crossings = 0;
  // throw until we have enough lines that actually cross the circle
  while (crossings < N) {
    // a random line: random angle φ and a random point it passes through in the window
    const phi = Math.PI * rnd();                       // orientation in [0,π)
    const px = (rnd() * 2 - 1) * win + cx;             // a point in the window (centred on circle)
    const py = (rnd() * 2 - 1) * win + cy;
    // perpendicular distance from circle centre (cx,cy) to the line through (px,py) at angle phi
    const nx = -Math.sin(phi), ny = Math.cos(phi);     // unit normal to the line
    const dist = Math.abs((px - cx) * nx + (py - cy) * ny);
    if (dist >= R) continue;                            // line misses the circle
    crossings++;
    if (2 * Math.sqrt(R * R - dist * dist) > SIDE) hit++;  // i.e. dist < R/2
  }
  return hit / crossings;
}
{
  // The straw-drop only equals the kinematic measure in the LARGE-WINDOW limit:
  // a finite window biases the perpendicular-distance law slightly, and the bias
  // shrinks as the window grows. These runs compare windows 4, 40 and 400 with
  // the 1/2 limit. The final run shifts both circle and window; the radius stays
  // fixed throughout. Moving only the circle within a fixed line distribution
  // is not tested here.
  const w4   = randomLineMethod(0xD00D, 4,   0, 0);
  const w40  = randomLineMethod(0xD11D, 40,  0, 0);
  const w400 = randomLineMethod(0xD33D, 400, 0, 0);
  check('D) random line, window=40  (→1/2)',  w40,  1 / 2);
  check('D) random line, window=400 (→1/2)',  w400, 1 / 2);
  check('D) straw-drop bias shrinks as window grows',
        Math.abs(w400 - 0.5) < Math.abs(w4 - 0.5) ? 1 : 0, 1, 0);
  check('D) random line, circle and window shifted together (R=1)',
        randomLineMethod(0xD22D, 40, 2.3, -1.7), 1 / 2);
}

// ---- the three answers are genuinely different (the paradox) ------------------
check('answers differ: 1/3 ≠ 1/2', Math.abs(1 / 3 - 1 / 2) > 0.1 ? 1 : 0, 1, 0);
check('answers differ: 1/2 ≠ 1/4', Math.abs(1 / 2 - 1 / 4) > 0.1 ? 1 : 0, 1, 0);

// ---- report ------------------------------------------------------------------
console.log('Bertrand\'s paradox — verifier\n' + '-'.repeat(60));
for (const line of log) console.log(line);
console.log('-'.repeat(60));
console.log(`${pass}/${pass + fail} checks pass` + (fail ? `  (${fail} FAILED)` : ''));
process.exit(fail ? 1 : 0);
