//! The dice are fair (docs/dice.md): a million throws of each die size the //! site rolls, checked with Pearson's chi-square goodness-of-fit test. //! //! A die fails when its counts are so uneven that a fair die would do as //! badly less than once in a million runs (p < 0.000001), so this never //! fails by chance in practice, yet a die with even a small lean fails it //! every time: `a_biased_die_fails` shows the modulo bias that rejection //! sampling exists to prevent being caught. use engine::{DiceSource, SecureDice}; const THROWS: u32 = 1_000_000; /// How unlikely a fair die's result has to be before we call it unfair. const ALPHA: f64 = 1e-6; /// Pearson's chi-square statistic for `counts` against a uniform die. fn chi_square(counts: &[u32]) -> f64 { let total: u32 = counts.iter().sum(); let expected = f64::from(total) / counts.len() as f64; counts .iter() .map(|&n| (f64::from(n) - expected).powi(2) / expected) .sum() } /// The chance a fair die with `df` degrees of freedom scores `statistic` /// or worse: the upper regularized gamma function Q(df/2, statistic/2), /// as 1 minus its lower series. fn p_value(statistic: f64, df: u32) -> f64 { let a = f64::from(df) / 2.0; let x = statistic / 2.0; let mut term = 1.0 / a; let mut sum = term; let mut n = 1.0; while term > sum * 1e-17 { term *= x / (a + n); sum += term; n += 1.0; } (1.0 - sum * (a * x.ln() - x - ln_gamma_half(df)).exp()).max(0.0) } /// ln Γ(df/2), exactly: Γ(1) = 1, Γ(1/2) = √π, Γ(a+1) = aΓ(a). fn ln_gamma_half(df: u32) -> f64 { let (mut a, mut ln) = if df.is_multiple_of(2) { (1.0, 0.0) } else { (0.5, std::f64::consts::PI.sqrt().ln()) }; while a < f64::from(df) / 2.0 { ln += a.ln(); a += 1.0; } ln } fn throw(dice: &mut dyn DiceSource, sides: u8) -> Vec { let mut counts = vec![0u32; usize::from(sides)]; for _ in 0..THROWS { let face = dice.die(sides); assert!((1..=sides).contains(&face), "d{sides} rolled {face}"); counts[usize::from(face - 1)] += 1; } counts } fn assert_fair(sides: u8) { let counts = throw(&mut SecureDice, sides); let statistic = chi_square(&counts); let p = p_value(statistic, u32::from(sides) - 1); assert!( p > ALPHA, "d{sides}: chi-square {statistic:.1}, p = {p:e}, counts {counts:?}" ); } #[test] fn d3_is_fair() { assert_fair(3); } #[test] fn d6_is_fair() { assert_fair(6); } #[test] fn d20_is_fair() { assert_fair(20); } #[test] fn d100_is_fair() { assert_fair(100); } /// A byte taken modulo the sides with no rejection: on a d100, faces 1–56 /// come up 3 times in 256 and the rest 2 in 256. struct ModuloDice; impl DiceSource for ModuloDice { fn die(&mut self, sides: u8) -> u8 { let mut byte = [0u8; 1]; getrandom::fill(&mut byte).unwrap(); byte[0] % sides + 1 } } #[test] fn a_biased_die_fails() { let counts = throw(&mut ModuloDice, 100); assert!(p_value(chi_square(&counts), 99) < ALPHA); } #[test] fn p_values_match_published_tables() { // Two degrees of freedom has the closed form e^(-x/2). assert!((p_value(27.631, 2) - 1e-6).abs() < 1e-9); // Standard table values: 11.070 at p = 0.05 for 5, 36.191 at 0.01 for 19, // 123.225 at 0.05 for 99. assert!((p_value(11.070, 5) - 0.05).abs() < 1e-4); assert!((p_value(36.191, 19) - 0.01).abs() < 1e-4); assert!((p_value(123.225, 99) - 0.05).abs() < 1e-4); }