1//! Fast approximation of `1/x`.
2//!
3//! Method described at: <https://bits.stephan-brumme.com/inverse.html>
4
5use super::F32;
6
7impl F32 {
8 /// Fast approximation of `1/x`.
9 pub fn inv(self) -> Self {
10 Self(f32::from_bits(0x7f00_0000 - self.0.to_bits()))
11 }
12}
13
14#[cfg(test)]
15pub(crate) mod tests {
16 use super::F32;
17
18 /// Deviation from the actual value (8%)
19 pub(crate) const MAX_ERROR: f32 = 0.08;
20
21 #[test]
22 fn sanity_check() {
23 for x in 0..100 {
24 let x = F32(x as f32);
25 let inv_x = x.inv().0;
26 let expected = 1.0 / x;
27 let allowed_delta = x * MAX_ERROR;
28 let actual_delta = inv_x - expected;
29
30 assert!(
31 actual_delta <= allowed_delta,
32 "delta {} too large: {} vs {}",
33 actual_delta,
34 inv_x,
35 expected
36 );
37 }
38 }
39}
40