Skip to main content

tpt_math_prob_core/
lib.rs

1#![no_std]
2//! Shared randomness traits for the `tpt-math-prob-*` family.
3//!
4//! This crate defines the traits the probability crates implement against:
5//!
6//! * [`Rng`] — a minimal source of pseudo-random bits (no `std`, no `alloc`).
7//! * [`Distribution<T>`] — a thing that can draw a value of type `T`.
8//! * [`Sampler<T>`] — blanket-implemented for every [`Distribution`], adding
9//!   bulk-sampling helpers that write into a caller-provided slice.
10//!
11//! It also ships [`SplitMix64`], a small deterministic PRNG, so consumers have
12//! a working `Rng` even in `no_std` environments where `rand` is unavailable.
13//!
14//! # Examples
15//!
16//! ```
17//! use tpt_math_prob_core::{Rng, Distribution, Standard, SplitMix64};
18//!
19//! let mut rng = SplitMix64::seed_from_u64(42);
20//! let x: f64 = Standard.sample(&mut rng);
21//! assert!((0.0..=1.0).contains(&x));
22//! ```
23//!
24//! [`Rng`]: Rng
25//! [`Distribution<T>`]: Distribution
26//! [`Sampler<T>`]: Sampler
27
28pub use tpt_math_numeric as numeric;
29
30// The `special` module uses `f64` transcendental methods, which live in `std`.
31#[cfg(feature = "std")]
32extern crate std;
33
34/// Special functions (log-gamma, incomplete gamma/beta, erf, normal CDF).
35#[cfg(feature = "std")]
36pub mod special;
37
38/// A source of pseudo-random bits.
39///
40/// Implementors must provide [`next_u64`](Rng::next_u64); `next_f64` is
41/// provided with a sensible default.
42pub trait Rng {
43    /// Return the next 64 bits of pseudo-random output.
44    fn next_u64(&mut self) -> u64;
45
46    /// Return the next `f64` uniformly distributed in `[0, 1)`.
47    fn next_f64(&mut self) -> f64 {
48        const SCALE: f64 = 1.0 / ((1u64 << 53) as f64);
49        ((self.next_u64() >> 11) as f64) * SCALE
50    }
51}
52
53/// A distribution that can produce samples of type `T`.
54pub trait Distribution<T> {
55    /// Draw a single sample using `rng`.
56    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> T;
57}
58
59/// Bulk sampling for any [`Distribution`].
60///
61/// Every [`Distribution`] automatically implements `Sampler` via the blanket
62/// impl below, gaining [`sample_slice`](Sampler::sample_slice).
63pub trait Sampler<T>: Distribution<T> {
64    /// Draw a single sample (default: delegate to [`Distribution::sample`]).
65    fn sample_one<R: Rng + ?Sized>(&self, rng: &mut R) -> T
66    where
67        T: Sized,
68    {
69        self.sample(rng)
70    }
71
72    /// Fill `buf` with independent samples.
73    fn sample_slice<R: Rng + ?Sized>(&self, rng: &mut R, buf: &mut [T])
74    where
75        T: Sized,
76    {
77        for slot in buf.iter_mut() {
78            *slot = self.sample(rng);
79        }
80    }
81}
82
83impl<D, T> Sampler<T> for D where D: Distribution<T> {}
84
85/// The standard uniform distribution over the type's natural range.
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
87pub struct Standard;
88
89impl Distribution<f64> for Standard {
90    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {
91        rng.next_f64()
92    }
93}
94
95impl Distribution<f32> for Standard {
96    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f32 {
97        rng.next_f64() as f32
98    }
99}
100
101impl Distribution<u64> for Standard {
102    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u64 {
103        rng.next_u64()
104    }
105}
106
107impl Distribution<u32> for Standard {
108    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u32 {
109        (rng.next_u64() >> 32) as u32
110    }
111}
112
113impl Distribution<i64> for Standard {
114    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> i64 {
115        rng.next_u64() as i64
116    }
117}
118
119impl Distribution<bool> for Standard {
120    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> bool {
121        (rng.next_u64() & 1) == 1
122    }
123}
124
125/// `SplitMix64`: a tiny, fast, deterministic 64-bit PRNG.
126///
127/// Not cryptographically secure, but excellent for reproducible tests,
128/// simulations, and `no_std` use where `rand`'s generators are unavailable.
129#[derive(Clone, Debug, PartialEq, Eq)]
130pub struct SplitMix64 {
131    state: u64,
132}
133
134impl SplitMix64 {
135    /// Create a generator from an explicit 64-bit state.
136    pub fn new(state: u64) -> Self {
137        SplitMix64 { state }
138    }
139
140    /// Create a generator seeded from a `u64` (the canonical entry point).
141    pub fn seed_from_u64(seed: u64) -> Self {
142        SplitMix64::new(seed.wrapping_add(0x9E37_79B9_7F4A_7C15))
143    }
144}
145
146impl Rng for SplitMix64 {
147    fn next_u64(&mut self) -> u64 {
148        self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
149        let mut z = self.state;
150        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
151        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
152        z ^ (z >> 31)
153    }
154}
155
156/// Any mutable reference to an [`Rng`] is itself an [`Rng`].
157///
158/// This lets a borrowed generator be passed to APIs that take `&mut impl Rng`
159/// (e.g. the sampler helpers) without cloning the underlying state.
160impl<R: Rng + ?Sized> Rng for &mut R {
161    fn next_u64(&mut self) -> u64 {
162        (**self).next_u64()
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn splitmix64_is_deterministic() {
172        let mut a = SplitMix64::seed_from_u64(1);
173        let mut b = SplitMix64::seed_from_u64(1);
174        for _ in 0..100 {
175            assert_eq!(a.next_u64(), b.next_u64());
176        }
177    }
178
179    #[test]
180    fn standard_f64_is_in_unit_interval() {
181        let mut rng = SplitMix64::seed_from_u64(7);
182        for _ in 0..1000 {
183            let x: f64 = Standard.sample(&mut rng);
184            assert!((0.0..=1.0).contains(&x));
185        }
186    }
187
188    #[test]
189    fn sampler_fills_slice() {
190        let mut rng = SplitMix64::seed_from_u64(99);
191        let mut buf = [0u64; 8];
192        Standard.sample_slice(&mut rng, &mut buf);
193        assert_ne!(buf, [0u64; 8]);
194    }
195}