Skip to main content

rand_float/
campbell.rs

1// Derived from binary64fast.c and random_real.c by Taylor R. Campbell,
2// distributed under the following license:
3//
4// Copyright (c) 2014-2026 Taylor R. Campbell
5// All rights reserved.
6//
7// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
10// 1. Redistributions of source code must retain the above copyright
11//    notice, this list of conditions and the following disclaimer.
12// 2. Redistributions in binary form must reproduce the above copyright
13//    notice, this list of conditions and the following disclaimer in the
14//    documentation and/or other materials provided with the distribution.
15//
16// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19// ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26// SUCH DAMAGE.
27
28//! Taylor R. Campbell’s correctly rounded uniform doubles.
29//!
30//! A Rust port of `binary64fast.c` (Campbell, 2014–2026) and of the
31//! `random_real` function of
32//! [`random_real.c`](https://mumble.net/~campbell/2014/04/28/random_real.c)
33//! (Campbell, 2014). These functions return an `f64` distributed as a uniform
34//! real in [0 . . 1] correctly rounded to nearest. The `binary64fast.c`
35//! functions ([`fast`] and the const-time variants) stop after two exponent
36//! words, so they reach every float in [2⁻¹²⁸ . . 1], each with
37//! probability equal to the measure of the reals that round to it, except
38//! that the reals below 2⁻¹²⁸ (probability 2⁻¹²⁸) are folded into the bottom
39//! binade. In particular, 0 never occurs: [`real`] keeps consuming words,
40//! and reaches every float in [2⁻¹⁰²⁴ . . 1], plus 0 (see its documentation
41//! for why the smaller subnormals cannot occur).
42//!
43//! Two variants handle the zero-`m` event without data-dependent branching, for
44//! use where timing side channels matter; they unconditionally consume three
45//! words per call. The `cmov` variant is a modification of mine in which the
46//! “bit smearing“ technique of the original C is replaced by a comparison that
47//! the compiler can turn into a conditional-move instruction (Taylor does not
48//! want to rely on the compiler for the absence of tests, but the smearing is
49//! much slower.)
50//!
51//! If you compare generated code with older copies of `binary64fast.c` you
52//! might find a signed where an unsigned integer-to-double conversion
53//! instruction was present: Taylor fixed the code after I reported the
54//! possibility of a branchy unsigned conversion on pre-AVX-512 x86.
55
56/// 2⁻⁶⁴ (Rust has no hex float literals; built via the exponent field).
57const TWO_M64: f64 = f64::from_bits((1023 - 64) << 52);
58/// 2³², used by the x86-only split unsigned→double conversion.
59#[cfg(target_arch = "x86_64")]
60const TWO_P32: f64 = 4294967296.0;
61
62/// Port of Campbell’s `uniformbinary64_fastdet`, the deterministic core of
63/// this module: turns an exponent scale `f` ∈ {2⁻⁶⁴, 2⁻¹²⁸}, a geometric
64/// word `m` and a significand word `u` into a correctly rounded (to
65/// nearest) uniform binary64.
66#[inline(always)]
67pub const fn fastdet(f: f64, m: u64, u: u64) -> f64 {
68    // Largest power-of-two divisor of m, with bit 63 forced as a backstop
69    // against a broken all-zero source; exactly representable, so the
70    // conversion below is exact.
71    let m = m | (1 << 63);
72    let m = m & m.wrapping_neg();
73    // On x86_64 there is no unsigned 64-bit → double instruction until
74    // AVX-512; split into halves so the compiler emits branch-free signed
75    // conversions, as in the C original.
76    #[cfg(target_arch = "x86_64")]
77    let d = ((m >> 32) as f64) * TWO_P32 + ((m & 0xFFFF_FFFF) as f64);
78    #[cfg(not(target_arch = "x86_64"))]
79    let d = m as f64;
80
81    // Uniform odd integer in (2⁶³..2⁶⁴): round-to-odd of a uniform real in
82    // [2⁶³..2⁶⁴]. The conversion rounds to nearest; ties are impossible.
83    let u = u | (1 << 63) | 1;
84    let s = u as f64;
85
86    // Scale the significand into [1/2..1] and apply the geometric exponent.
87    s * f / d
88}
89
90/// Port of `uniformbinary64_fast`: a correctly rounded (to nearest) uniform
91/// real in [0 . . 1], branching on the 2⁻⁶⁴-probability zero-`m` event.
92///
93/// Consumes two 64-bit words, plus a third with probability 2⁻⁶⁴.
94#[inline(always)]
95pub fn fast(mut bits: impl FnMut() -> u64) -> f64 {
96    let u = bits();
97    let mut f = TWO_M64;
98    let mut m = bits();
99    if m == 0 {
100        // unlikely
101        f *= TWO_M64;
102        m = bits();
103    }
104    fastdet(f, m, u)
105}
106
107/// Shared tail of the const-time variants: given the flag t ∈ {0, 1}
108/// (t = 1 iff m ≠ 0), rescale `f` and substitute `m2` for a zero `m`,
109/// both branch-free. See the [module documentation](self) for the
110/// signed-arithmetic form of the rescaling.
111#[inline(always)]
112const fn consttime_tail(t: u64, u: u64, m: u64, m2: u64) -> f64 {
113    let mut f = TWO_M64;
114    let tf = t as i64 as f64;
115    f *= tf - (tf - 1.0) * TWO_M64;
116    let m = m | (m2 & t.wrapping_sub(1));
117    fastdet(f, m, u)
118}
119
120/// Port of `uniformbinary64_consttime_if`: like [`fast`], but the zero-`m`
121/// event is branchless, with the flag computed as `m != 0`.
122///
123/// This is a small variant of mine: it relies on the compiler turning the
124/// comparison into a conditional-move–style instruction (`setne`, `cset`)
125/// rather than a branch. Taylor prefers the bit-smearing variant
126/// ([`consttime`]) because, for security reasons, it guarantees at the source
127/// level that no test can be inserted by the compiler, whereas here the absence
128/// of a branch is at the optimizer's discretion.
129///
130/// Always consumes three 64-bit words.
131#[inline(always)]
132pub fn consttime_cmove(mut bits: impl FnMut() -> u64) -> f64 {
133    let (u, m, m2) = (bits(), bits(), bits());
134    let t = (m != 0) as u64;
135    consttime_tail(t, u, m, m2)
136}
137
138/// Port of `uniformbinary64_consttime_smear`: like [`consttime_cmove`], but the
139/// flag is computed by smearing every set bit of `m` down to bit 0, so it is
140/// branchless at the source level, independently of the compiler. This is the
141/// variant Taylor prefers for security-sensitive uses, since no
142/// compiler-inserted test can leak the (secret) value of `m` through a timing
143/// side channel.
144///
145/// Always consumes three 64-bit words.
146#[inline(always)]
147pub fn consttime(mut bits: impl FnMut() -> u64) -> f64 {
148    let (u, m, m2) = (bits(), bits(), bits());
149    let mut t = m;
150    t |= t >> 1;
151    t |= t >> 2;
152    t |= t >> 4;
153    t |= t >> 8;
154    t |= t >> 16;
155    t |= t >> 32;
156    t &= 1;
157    consttime_tail(t, u, m, m2)
158}
159
160/// 2⁻⁹⁶⁰, the exact first stage of the two-step scaling that replaces
161/// the C original's `ldexp`.
162const TWO_M960: f64 = f64::from_bits((1023 - 960) << 52);
163
164/// Port of `random_real` from `random_real.c`: interprets an unbounded
165/// stream of random bits as the binary expansion of a real number in
166/// [0 . . 1] and rounds it to the nearest `f64`, with a sticky bit avoiding
167/// ties. Every float in [2⁻¹⁰²⁴ . . 1] is reachable; 0 is returned after
168/// 1024 zero bits (probability 2⁻¹⁰²⁴, i.e., only if the source is broken),
169/// and the subnormals below 2⁻¹⁰²⁴ cannot occur.
170///
171/// This documentation differs from the comments in the C original, which
172/// claims to reach every float in [0 . . 1] and to return 0 only when the
173/// result is guaranteed to round to zero: the all-zeros cutoff fires one
174/// word too early (after 16 rather than 17 zero words) discarding
175/// continuations as large as ≈2⁻¹⁰²⁴ that would round to smaller
176/// subnormals. This is a minor bug we found while porting and reported to
177/// the author; it affects an event of probability 2⁻¹⁰²⁴, and the code
178/// below is left faithful to the original.
179///
180/// Consumes one 64-bit word, plus one more with probability 1/2 (when the
181/// first word has leading zeros), plus one word per 64 leading zero bits.
182/// The expected number of words per call is ≈1.5.
183///
184/// The C original scales by `ldexp(significand, exponent)`; Rust has no
185/// `ldexp` in the standard library, and a single multiplication cannot
186/// replace it, since 2^exponent can be as small as 2⁻¹⁰⁸⁷, which is not
187/// representable. The port multiplies by 2⁻⁹⁶⁰ first (exact, since the
188/// intermediate result stays normal) and then by 2^(exponent + 960),
189/// which is always representable, so the result is rounded once, exactly
190/// as in `ldexp`.
191#[inline(always)]
192pub fn real(mut bits: impl FnMut() -> u64) -> f64 {
193    let mut exponent = -64i32;
194
195    // Read zeros into the exponent until we hit a one; the rest will go
196    // into the significand.
197    let mut significand = bits();
198    while significand == 0 {
199        exponent -= 64;
200        // The C original claims that below -1074 = emin + 1 - p the result
201        // is guaranteed to round to zero, but the check fires one word too
202        // early (see the doc comment); kept as is for faithfulness to the
203        // original. This can happen in realistic terms only if the source
204        // is broken.
205        if exponent < -1074 {
206            return 0.0;
207        }
208        significand = bits();
209    }
210
211    // If there are leading zeros, shift them into the exponent and refill
212    // the less-significant bits of the significand.
213    let shift = significand.leading_zeros();
214    if shift != 0 {
215        exponent -= shift as i32;
216        significand <<= shift;
217        significand |= bits() >> (64 - shift);
218    }
219
220    // Set the sticky bit, since there is almost surely another 1 in the
221    // bit stream; otherwise an apparent tie might round to even when,
222    // almost surely, a further 1 would break it.
223    significand |= 1;
224
225    // ldexp(significand as f64, exponent), in two multiplications: the
226    // first is exact, the second rounds (to a subnormal, possibly).
227    significand as f64 * TWO_M960 * f64::from_bits(((1023 + 960 + exponent) as u64) << 52)
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233    use crate::sources::Weyl;
234
235    /// 2⁻¹²⁸.
236    const TWO_M128: f64 = f64::from_bits((1023 - 128) << 52);
237
238    /// A source that replays a fixed sequence of words, then panics.
239    fn replay(words: &[u64]) -> impl FnMut() -> u64 + '_ {
240        let mut iter = words.iter();
241        move || *iter.next().expect("source exhausted")
242    }
243
244    #[test]
245    fn test_stays_in_closed_unit_interval() {
246        let mut rng = Weyl(42);
247        for _ in 0..100_000 {
248            let x = fast(|| rng.next_u64());
249            assert!(x > 0.0 && x <= 1.0, "fast: {x}");
250            let x = consttime_cmove(|| rng.next_u64());
251            assert!(x > 0.0 && x <= 1.0, "consttime_cmove: {x}");
252            let x = consttime(|| rng.next_u64());
253            assert!(x > 0.0 && x <= 1.0, "consttime: {x}");
254        }
255    }
256
257    /// The two const-time variants must agree on every input.
258    #[test]
259    fn test_consttime_variants_agree() {
260        let mut rng = Weyl(0xDEAD_BEEF);
261        for _ in 0..100_000 {
262            let words = [rng.next_u64(), rng.next_u64(), rng.next_u64()];
263            assert_eq!(consttime_cmove(replay(&words)), consttime(replay(&words)));
264        }
265    }
266
267    /// With a nonzero m, the const-time variants must agree with the
268    /// branchy variant (which then ignores the third word).
269    #[test]
270    fn test_consttime_agrees_with_fast() {
271        let mut rng = Weyl(0xBADC_0FFE);
272        for _ in 0..100_000 {
273            let words = [rng.next_u64(), rng.next_u64().max(1), rng.next_u64()];
274            assert_eq!(fast(replay(&words[..2])), consttime_cmove(replay(&words)));
275        }
276    }
277
278    /// The signed-arithmetic fix: with m = 0 the scale must become 2⁻¹²⁸
279    /// (not go negative as with the unsigned `(t - 1)` of the original C).
280    #[test]
281    fn test_consttime_zero_mantissa_rescales() {
282        let u = 0x0123_4567_89AB_CDEF;
283        let m2 = 0x8000_0000_0000_0000u64; // power of two: d = 2^63
284        let x = consttime_cmove(replay(&[u, 0, m2]));
285        assert!(x > 0.0, "scale went negative: {x}");
286        // s ≈ 2^63, f = 2^-128, d = 2^63  ⇒  x ≈ 2^-128.
287        assert_eq!(x, fastdet(TWO_M128, m2, u));
288        // And with m ≠ 0, m2 must be ignored.
289        assert_eq!(consttime_cmove(replay(&[u, 3, m2])), fastdet(TWO_M64, 3, u));
290    }
291
292    /// Known values of `real`, pinning the two-step `ldexp` replacement
293    /// (verified bit-for-bit against the compiled C original).
294    #[test]
295    fn test_real_known_values() {
296        // Top bit set: one word, no refill; 2^63 | 1 rounds to 2^63.
297        assert_eq!(real(replay(&[1 << 63])), 0.5);
298        // All ones rounds up to 2^64: the maximum output, exactly 1.
299        assert_eq!(real(replay(&[!0])), 1.0);
300        // Smallest first word: 63 leading zeros shifted out and refilled.
301        assert_eq!(real(replay(&[1, 0])), f64::from_bits((1023 - 64) << 52)); // 2^-64
302        // 15 zero words then a 1: deep subnormal, 2^-1024.
303        let mut words = [0u64; 17];
304        words[15] = 1;
305        assert_eq!(real(replay(&words)), f64::from_bits(1 << 50));
306        // 16 zero words: the exponent falls below -1074 and the result is 0.
307        assert_eq!(real(replay(&[0u64; 16])), 0.0);
308    }
309
310    #[test]
311    fn test_real_stays_in_closed_unit_interval() {
312        let mut rng = Weyl(7);
313        for _ in 0..100_000 {
314            let x = real(|| rng.next_u64());
315            assert!(x > 0.0 && x <= 1.0, "real: {x}");
316        }
317    }
318}