stdrandom 0.3.0

Generate random numbers using only Rust standard library
Documentation
use stdrandom::fast_u64;
use stdrandom::random_u64;

fn chi_square(observed: &[u32; 16], expected: f64) -> f64 {
    observed
        .iter()
        .map(|&obs| {
            let diff = obs as f64 - expected;
            (diff * diff) / expected
        })
        .sum()
}

#[test]
#[ignore]
fn test_chi_square_randomness() {
    let mut hist_upper = [0; 16];
    let mut hist_lower = [0; 16];

    let samples = 300_000;
    let expected = samples as f64 / 16.0; // Expected uniform distribution

    // Collect histogram data
    for _ in 0..samples {
        let num = random_u64();
        hist_upper[(num >> 60) as usize] += 1; // Highest 4 bits
        hist_lower[(num & 0xF) as usize] += 1; // Lowest 4 bits
    }

    let chi_upper = chi_square(&hist_upper, expected);
    let chi_lower = chi_square(&hist_lower, expected);

    println!("Upper bits chi-square: {:.4}", chi_upper);
    println!("Lower bits chi-square: {:.4}", chi_lower);

    // Chi-square critical value for 15 degrees of freedom (p=0.05) ~ 24.99
    assert!(
        chi_upper < 24.99,
        "Upper bits deviate significantly from uniform distribution!"
    );
    assert!(
        chi_lower < 24.99,
        "Lower bits deviate significantly from uniform distribution!"
    );
    panic!("");
}

#[test]
#[ignore]
fn test_chi_square_fast_randomness() {
    let mut hist_upper = [0; 16];
    let mut hist_lower = [0; 16];

    let samples = 2_500_000;
    let expected = samples as f64 / 16.0; // Expected uniform distribution

    // Collect histogram data
    for _ in 0..samples {
        let num = fast_u64();
        hist_upper[(num >> 60) as usize] += 1; // Highest 4 bits
        hist_lower[(num & 0xF) as usize] += 1; // Lowest 4 bits
    }

    let chi_upper = chi_square(&hist_upper, expected);
    let chi_lower = chi_square(&hist_lower, expected);

    println!("Upper bits chi-square: {:.4}", chi_upper);
    println!("Lower bits chi-square: {:.4}", chi_lower);

    // Chi-square critical value for 15 degrees of freedom (p=0.05) ~ 24.99
    assert!(
        chi_upper < 24.99,
        "Upper bits deviate significantly from uniform distribution!"
    );
    assert!(
        chi_lower < 24.99,
        "Lower bits deviate significantly from uniform distribution!"
    );
    panic!("");
}