libm/math/log1pf.rs
1/* origin: FreeBSD /usr/src/lib/msun/src/s_log1pf.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
13const LN2_HI: f32 = 6.9313812256e-01; /* 0x3f317180 */
14const LN2_LO: f32 = 9.0580006145e-06; /* 0x3717f7d1 */
15/* |(log(1+s)-log(1-s))/s - Lg(s)| < 2**-34.24 (~[-4.95e-11, 4.97e-11]). */
16const LG1: f32 = 0.66666662693; /* 0xaaaaaa.0p-24 */
17const LG2: f32 = 0.40000972152; /* 0xccce13.0p-25 */
18const LG3: f32 = 0.28498786688; /* 0x91e9ee.0p-25 */
19const LG4: f32 = 0.24279078841; /* 0xf89e26.0p-26 */
20
21/// The natural logarithm of 1+`x` (f32).
22#[cfg_attr(assert_no_panic, no_panic::no_panic)]
23pub fn log1pf(x: f32) -> f32 {
24 let mut ui: u32 = x.to_bits();
25 let hfsq: f32;
26 let mut f: f32 = 0.;
27 let mut c: f32 = 0.;
28 let s: f32;
29 let z: f32;
30 let r: f32;
31 let w: f32;
32 let t1: f32;
33 let t2: f32;
34 let dk: f32;
35 let ix: u32;
36 let mut iu: u32;
37 let mut k: i32;
38
39 ix = ui;
40 k = 1;
41 if ix < 0x3ed413d0 || (ix >> 31) > 0 {
42 /* 1+x < sqrt(2)+ */
43 if ix >= 0xbf800000 {
44 /* x <= -1.0 */
45 if x == -1. {
46 return x / 0.0; /* log1p(-1)=+inf */
47 }
48 return (x - x) / 0.0; /* log1p(x<-1)=NaN */
49 }
50 if ix << 1 < 0x33800000 << 1 {
51 /* |x| < 2**-24 */
52 /* underflow if subnormal */
53 if (ix & 0x7f800000) == 0 {
54 force_eval!(x * x);
55 }
56 return x;
57 }
58 if ix <= 0xbe95f619 {
59 /* sqrt(2)/2- <= 1+x < sqrt(2)+ */
60 k = 0;
61 c = 0.;
62 f = x;
63 }
64 } else if ix >= 0x7f800000 {
65 return x;
66 }
67 if k > 0 {
68 ui = (1. + x).to_bits();
69 iu = ui;
70 iu += 0x3f800000 - 0x3f3504f3;
71 k = (iu >> 23) as i32 - 0x7f;
72 /* correction term ~ log(1+x)-log(u), avoid underflow in c/u */
73 if k < 25 {
74 c = if k >= 2 {
75 1. - (f32::from_bits(ui) - x)
76 } else {
77 x - (f32::from_bits(ui) - 1.)
78 };
79 c /= f32::from_bits(ui);
80 } else {
81 c = 0.;
82 }
83 /* reduce u into [sqrt(2)/2, sqrt(2)] */
84 iu = (iu & 0x007fffff) + 0x3f3504f3;
85 ui = iu;
86 f = f32::from_bits(ui) - 1.;
87 }
88 s = f / (2.0 + f);
89 z = s * s;
90 w = z * z;
91 t1 = w * (LG2 + w * LG4);
92 t2 = z * (LG1 + w * LG3);
93 r = t2 + t1;
94 hfsq = 0.5 * f * f;
95 dk = k as f32;
96 s * (hfsq + r) + (dk * LN2_LO + c) - hfsq + f + dk * LN2_HI
97}