| 1 | //! log base 2 approximation for a single-precision float. |
| 2 | |
| 3 | use super::F32; |
| 4 | use core::f32::consts::LOG2_E; |
| 5 | |
| 6 | impl F32 { |
| 7 | /// Approximates the base 2 logarithm of the number. |
| 8 | pub fn log2(self) -> Self { |
| 9 | self.ln() * LOG2_E |
| 10 | } |
| 11 | } |
| 12 | |
| 13 | #[cfg (test)] |
| 14 | mod tests { |
| 15 | use super::F32; |
| 16 | |
| 17 | pub(crate) const MAX_ERROR: f32 = 0.001; |
| 18 | |
| 19 | /// log2(x) test vectors - `(input, output)` |
| 20 | pub(crate) const TEST_VECTORS: &[(f32, f32)] = &[ |
| 21 | (1e-20, -66.43856), |
| 22 | (1e-19, -63.116634), |
| 23 | (1e-18, -59.794704), |
| 24 | (1e-17, -56.47278), |
| 25 | (1e-16, -53.15085), |
| 26 | (1e-15, -49.828922), |
| 27 | (1e-14, -46.506992), |
| 28 | (1e-13, -43.185066), |
| 29 | (1e-12, -39.863136), |
| 30 | (1e-11, -36.54121), |
| 31 | (1e-10, -33.21928), |
| 32 | (1e-09, -29.897352), |
| 33 | (1e-08, -26.575424), |
| 34 | (1e-07, -23.253496), |
| 35 | (1e-06, -19.931568), |
| 36 | (1e-05, -16.60964), |
| 37 | (1e-04, -13.287712), |
| 38 | (0.001, -9.965784), |
| 39 | (0.01, -6.643856), |
| 40 | (0.1, -3.321928), |
| 41 | (10.0, 3.321928), |
| 42 | (100.0, 6.643856), |
| 43 | (1000.0, 9.965784), |
| 44 | (10000.0, 13.287712), |
| 45 | (100000.0, 16.60964), |
| 46 | (1000000.0, 19.931568), |
| 47 | (10000000.0, 23.253496), |
| 48 | (100000000.0, 26.575424), |
| 49 | (1000000000.0, 29.897352), |
| 50 | (10000000000.0, 33.21928), |
| 51 | (100000000000.0, 36.54121), |
| 52 | (1000000000000.0, 39.863136), |
| 53 | (10000000000000.0, 43.185066), |
| 54 | (100000000000000.0, 46.506992), |
| 55 | (1000000000000000.0, 49.828922), |
| 56 | (1e+16, 53.15085), |
| 57 | (1e+17, 56.47278), |
| 58 | (1e+18, 59.794704), |
| 59 | (1e+19, 63.116634), |
| 60 | ]; |
| 61 | |
| 62 | #[test ] |
| 63 | fn sanity_check() { |
| 64 | assert_eq!(F32::ONE.log2(), F32::ZERO); |
| 65 | |
| 66 | for &(x, expected) in TEST_VECTORS { |
| 67 | let ln_x = F32(x).log2().0; |
| 68 | let relative_error = (ln_x - expected).abs() / expected; |
| 69 | |
| 70 | assert!( |
| 71 | relative_error <= MAX_ERROR, |
| 72 | "relative_error {} too large: {} vs {}" , |
| 73 | relative_error, |
| 74 | ln_x, |
| 75 | expected |
| 76 | ); |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |