Skip to main content

openqmc/
float.rs

1//! Port of `oqmc/float.h` — integer to `[0, 1)` float conversion.
2//!
3//! Uses the "clear the guard bit" trick (option 4 in the upstream header): by
4//! masking off the bit 24 places below the leading one, the default
5//! round-to-nearest conversion always rounds *down*, giving the optimal uniform
6//! probability density of Keller/Wächter/Binder without changing the FPU
7//! rounding mode, and guaranteeing an output strictly less than one.
8
9/// 2^-32.
10pub const FLOAT_ONE_OVER_TWO_POWER_32: f32 = 1.0 / 4294967296.0;
11
12/// Scale a 32-bit unsigned integer into a `[0, 1)` float.
13#[inline]
14pub fn uint_to_float(value: u32) -> f32 {
15    let mask = value >> 24;
16    let safe = value & !mask;
17    (safe as f32) * FLOAT_ONE_OVER_TWO_POWER_32
18}
19
20#[cfg(test)]
21mod tests {
22    use super::*;
23
24    // Largest f32 strictly below 1.0 == nextafterf(1.0, 0.0).
25    const ONE_MINUS_EPSILON: f32 = f32::from_bits(0x3f7f_ffff);
26
27    #[test]
28    fn one_over_two_power_32() {
29        assert_eq!(FLOAT_ONE_OVER_TWO_POWER_32, 1.0 / ((1u64 << 32) as f32));
30    }
31
32    #[test]
33    fn minimum() {
34        assert_eq!(uint_to_float(0), 0.0);
35        assert!(uint_to_float(1) > 0.0);
36        assert!(uint_to_float(1) < uint_to_float(2));
37    }
38
39    #[test]
40    fn maximum() {
41        assert_eq!(uint_to_float(u32::MAX), ONE_MINUS_EPSILON);
42    }
43
44    #[test]
45    fn high() {
46        // Exactly 256 inputs [0xffffff00, 0xffffffff] map to 1 - eps.
47        assert!(uint_to_float(0xffff_feff) < ONE_MINUS_EPSILON);
48        assert_eq!(uint_to_float(0xffff_ff00), ONE_MINUS_EPSILON);
49        assert_eq!(uint_to_float(0xffff_ff01), ONE_MINUS_EPSILON);
50        assert_eq!(uint_to_float(0xffff_ffff), ONE_MINUS_EPSILON);
51    }
52
53    #[test]
54    fn half() {
55        // Exactly 256 inputs [0x80000000, 0x800000ff] map to 0.5.
56        assert!(uint_to_float(0x7fff_ffff) < 0.5);
57        assert_eq!(uint_to_float(0x8000_0000), 0.5);
58        assert_eq!(uint_to_float(0x8000_0001), 0.5);
59        assert_eq!(uint_to_float(0x8000_00ff), 0.5);
60        assert!(uint_to_float(0x8000_0100) > 0.5);
61    }
62
63    #[test]
64    fn monotonic() {
65        let mut last = 0.0f32;
66        for i in 0..8u32 {
67            let step_int = u32::MAX / 8 * (i + 1);
68            let step = uint_to_float(step_int);
69            assert!(step > last);
70            last = step;
71        }
72    }
73}