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`.
162#[cfg(not(all(target_arch = "x86_64", target_feature = "avx512f")))]
163const TWO_M960: f64 = f64::from_bits((1023 - 960) << 52);
164
165/// `ldexp(significand as f64, exponent)` for the tail of [`real`]:
166/// AVX-512F provides `ldexp` in hardware (`vscalefsd`, x·2^⌊e⌋ with a
167/// single rounding, subnormals included), so a single instruction
168/// replaces the two-multiplication sequence of the portable version
169/// below.
170#[cfg(all(target_arch = "x86_64", target_feature = "avx512f"))]
171#[inline(always)]
172fn ldexp_sig(significand: u64, exponent: i32) -> f64 {
173    let x = significand as f64; // vcvtusi2sd: single instruction on AVX-512
174    let e = exponent as f64; // exact, and off the critical path
175    let r: f64;
176    // SAFETY: pure register-to-register scalar arithmetic; the cfg above
177    // guarantees the instruction set.
178    unsafe {
179        core::arch::asm!(
180            "vscalefsd {r}, {x}, {e}",
181            r = lateout(xmm_reg) r,
182            x = in(xmm_reg) x,
183            e = in(xmm_reg) e,
184            options(pure, nomem, nostack),
185        );
186    }
187    r
188}
189
190/// `ldexp(significand as f64, exponent)` in two multiplications: the
191/// first is exact, the second rounds (to a subnormal, possibly).
192#[cfg(not(all(target_arch = "x86_64", target_feature = "avx512f")))]
193#[inline(always)]
194fn ldexp_sig(significand: u64, exponent: i32) -> f64 {
195    significand as f64 * TWO_M960 * f64::from_bits(((1023 + 960 + exponent) as u64) << 52)
196}
197
198/// Port of `random_real` from `random_real.c`: interprets an unbounded
199/// stream of random bits as the binary expansion of a real number in
200/// [0 . . 1] and rounds it to the nearest `f64`, with a sticky bit avoiding
201/// ties. Every float in [2⁻¹⁰²⁴ . . 1] is reachable; 0 is returned after
202/// 1024 zero bits (probability 2⁻¹⁰²⁴, i.e., only if the source is broken),
203/// and the subnormals below 2⁻¹⁰²⁴ cannot occur.
204///
205/// This documentation differs from the comments in the C original, which
206/// claims to reach every float in [0 . . 1] and to return 0 only when the
207/// result is guaranteed to round to zero: the all-zeros cutoff fires one
208/// word too early (after 16 rather than 17 zero words) discarding
209/// continuations as large as ≈2⁻¹⁰²⁴ that would round to smaller
210/// subnormals. This is a minor bug we found while porting and reported to
211/// the author; it affects an event of probability 2⁻¹⁰²⁴, and the code
212/// below is left faithful to the original.
213///
214/// Consumes one 64-bit word, plus one more with probability 1/2 (when the
215/// first word has leading zeros), plus one word per 64 leading zero bits.
216/// The expected number of words per call is ≈1.5.
217///
218/// The C original scales by `ldexp(significand, exponent)`; Rust has no
219/// `ldexp` in the standard library, and a single multiplication cannot
220/// replace it, since 2^exponent can be as small as 2⁻¹⁰⁸⁷, which is not
221/// representable. The port multiplies by 2⁻⁹⁶⁰ first (exact, since the
222/// intermediate result stays normal) and then by 2^(exponent + 960),
223/// which is always representable, so the result is rounded once, exactly
224/// as in `ldexp`. On x86-64 compiled with AVX-512F the port uses instead
225/// the hardware `ldexp` (a single `vscalefsd` instruction) via inline
226/// assembly.
227#[inline(always)]
228pub fn real(mut bits: impl FnMut() -> u64) -> f64 {
229    let mut exponent = -64i32;
230
231    // Read zeros into the exponent until we hit a one; the rest will go
232    // into the significand.
233    let mut significand = bits();
234    while significand == 0 {
235        exponent -= 64;
236        // The C original claims that below -1074 = emin + 1 - p the result
237        // is guaranteed to round to zero, but the check fires one word too
238        // early (see the doc comment); kept as is for faithfulness to the
239        // original. This can happen in realistic terms only if the source
240        // is broken.
241        if exponent < -1074 {
242            return 0.0;
243        }
244        significand = bits();
245    }
246
247    // If there are leading zeros, shift them into the exponent and refill
248    // the less-significant bits of the significand.
249    let shift = significand.leading_zeros();
250    if shift != 0 {
251        exponent -= shift as i32;
252        significand <<= shift;
253        significand |= bits() >> (64 - shift);
254    }
255
256    // Set the sticky bit, since there is almost surely another 1 in the
257    // bit stream; otherwise an apparent tie might round to even when,
258    // almost surely, a further 1 would break it.
259    significand |= 1;
260
261    ldexp_sig(significand, exponent)
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267    use crate::sources::Weyl;
268
269    /// 2⁻¹²⁸.
270    const TWO_M128: f64 = f64::from_bits((1023 - 128) << 52);
271
272    /// A source that replays a fixed sequence of words, then panics.
273    fn replay(words: &[u64]) -> impl FnMut() -> u64 + '_ {
274        let mut iter = words.iter();
275        move || *iter.next().expect("source exhausted")
276    }
277
278    #[test]
279    fn test_stays_in_closed_unit_interval() {
280        let mut rng = Weyl(42);
281        for _ in 0..100_000 {
282            let x = fast(|| rng.next_u64());
283            assert!(x > 0.0 && x <= 1.0, "fast: {x}");
284            let x = consttime_cmove(|| rng.next_u64());
285            assert!(x > 0.0 && x <= 1.0, "consttime_cmove: {x}");
286            let x = consttime(|| rng.next_u64());
287            assert!(x > 0.0 && x <= 1.0, "consttime: {x}");
288        }
289    }
290
291    /// The two const-time variants must agree on every input.
292    #[test]
293    fn test_consttime_variants_agree() {
294        let mut rng = Weyl(0xDEAD_BEEF);
295        for _ in 0..100_000 {
296            let words = [rng.next_u64(), rng.next_u64(), rng.next_u64()];
297            assert_eq!(consttime_cmove(replay(&words)), consttime(replay(&words)));
298        }
299    }
300
301    /// With a nonzero m, the const-time variants must agree with the
302    /// branchy variant (which then ignores the third word).
303    #[test]
304    fn test_consttime_agrees_with_fast() {
305        let mut rng = Weyl(0xBADC_0FFE);
306        for _ in 0..100_000 {
307            let words = [rng.next_u64(), rng.next_u64().max(1), rng.next_u64()];
308            assert_eq!(fast(replay(&words[..2])), consttime_cmove(replay(&words)));
309        }
310    }
311
312    /// The signed-arithmetic fix: with m = 0 the scale must become 2⁻¹²⁸
313    /// (not go negative as with the unsigned `(t - 1)` of the original C).
314    #[test]
315    fn test_consttime_zero_mantissa_rescales() {
316        let u = 0x0123_4567_89AB_CDEF;
317        let m2 = 0x8000_0000_0000_0000u64; // power of two: d = 2^63
318        let x = consttime_cmove(replay(&[u, 0, m2]));
319        assert!(x > 0.0, "scale went negative: {x}");
320        // s ≈ 2^63, f = 2^-128, d = 2^63  ⇒  x ≈ 2^-128.
321        assert_eq!(x, fastdet(TWO_M128, m2, u));
322        // And with m ≠ 0, m2 must be ignored.
323        assert_eq!(consttime_cmove(replay(&[u, 3, m2])), fastdet(TWO_M64, 3, u));
324    }
325
326    /// Known values of `real`, pinning the two-step `ldexp` replacement
327    /// (verified bit-for-bit against the compiled C original).
328    #[test]
329    fn test_real_known_values() {
330        // Top bit set: one word, no refill; 2^63 | 1 rounds to 2^63.
331        assert_eq!(real(replay(&[1 << 63])), 0.5);
332        // All ones rounds up to 2^64: the maximum output, exactly 1.
333        assert_eq!(real(replay(&[!0])), 1.0);
334        // Smallest first word: 63 leading zeros shifted out and refilled.
335        assert_eq!(real(replay(&[1, 0])), f64::from_bits((1023 - 64) << 52)); // 2^-64
336        // 15 zero words then a 1: deep subnormal, 2^-1024.
337        let mut words = [0u64; 17];
338        words[15] = 1;
339        assert_eq!(real(replay(&words)), f64::from_bits(1 << 50));
340        // 16 zero words: the exponent falls below -1074 and the result is 0.
341        assert_eq!(real(replay(&[0u64; 16])), 0.0);
342    }
343
344    #[test]
345    fn test_real_stays_in_closed_unit_interval() {
346        let mut rng = Weyl(7);
347        for _ in 0..100_000 {
348            let x = real(|| rng.next_u64());
349            assert!(x > 0.0 && x <= 1.0, "real: {x}");
350        }
351    }
352}