1/* origin: FreeBSD /usr/src/lib/msun/src/e_log2f.c */
2/*
3 * ====================================================
4 * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
5 *
6 * Developed at SunPro, a Sun Microsystems, Inc. business.
7 * Permission to use, copy, modify, and distribute this
8 * software is freely granted, provided that this notice
9 * is preserved.
10 * ====================================================
11 */
12/*
13 * See comments in log2.c.
14 */
15
16use core::f32;
17
18const IVLN2HI: f32 = 1.4428710938e+00; /* 0x3fb8b000 */
19const IVLN2LO: f32 = -1.7605285393e-04; /* 0xb9389ad4 */
20/* |(log(1+s)-log(1-s))/s - Lg(s)| < 2**-34.24 (~[-4.95e-11, 4.97e-11]). */
21const LG1: f32 = 0.66666662693; /* 0xaaaaaa.0p-24 */
22const LG2: f32 = 0.40000972152; /* 0xccce13.0p-25 */
23const LG3: f32 = 0.28498786688; /* 0x91e9ee.0p-25 */
24const LG4: f32 = 0.24279078841; /* 0xf89e26.0p-26 */
25
26#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
27pub fn log2f(mut x: f32) -> f32 {
28 let x1p25f = f32::from_bits(0x4c000000); // 0x1p25f === 2 ^ 25
29
30 let mut ui: u32 = x.to_bits();
31 let hfsq: f32;
32 let f: f32;
33 let s: f32;
34 let z: f32;
35 let r: f32;
36 let w: f32;
37 let t1: f32;
38 let t2: f32;
39 let mut hi: f32;
40 let lo: f32;
41 let mut ix: u32;
42 let mut k: i32;
43
44 ix = ui;
45 k = 0;
46 if ix < 0x00800000 || (ix >> 31) > 0 {
47 /* x < 2**-126 */
48 if ix << 1 == 0 {
49 return -1. / (x * x); /* log(+-0)=-inf */
50 }
51 if (ix >> 31) > 0 {
52 return (x - x) / 0.0; /* log(-#) = NaN */
53 }
54 /* subnormal number, scale up x */
55 k -= 25;
56 x *= x1p25f;
57 ui = x.to_bits();
58 ix = ui;
59 } else if ix >= 0x7f800000 {
60 return x;
61 } else if ix == 0x3f800000 {
62 return 0.;
63 }
64
65 /* reduce x into [sqrt(2)/2, sqrt(2)] */
66 ix += 0x3f800000 - 0x3f3504f3;
67 k += (ix >> 23) as i32 - 0x7f;
68 ix = (ix & 0x007fffff) + 0x3f3504f3;
69 ui = ix;
70 x = f32::from_bits(ui);
71
72 f = x - 1.0;
73 s = f / (2.0 + f);
74 z = s * s;
75 w = z * z;
76 t1 = w * (LG2 + w * LG4);
77 t2 = z * (LG1 + w * LG3);
78 r = t2 + t1;
79 hfsq = 0.5 * f * f;
80
81 hi = f - hfsq;
82 ui = hi.to_bits();
83 ui &= 0xfffff000;
84 hi = f32::from_bits(ui);
85 lo = f - hi - hfsq + s * (hfsq + r);
86 (lo + hi) * IVLN2LO + lo * IVLN2HI + hi * IVLN2HI + k as f32
87}
88