1pub const FLOAT_ONE_OVER_TWO_POWER_32: f32 = 1.0 / 4294967296.0;
11
12#[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 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 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 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}