Skip to main content

libc_rs/
math.rs

1//! Pure-Rust `#![no_std]` floating-point intrinsics and hardware AArch64 instructions.
2
3const LN2_HI: f64 = 6.931_471_803_691_238e-1;
4const LN2_LO: f64 = 1.908_214_929_270_587_7e-10;
5const INV_LN2: f64 = core::f64::consts::LOG2_E;
6
7const LG1: f64 = 6.666_666_666_666_735e-1;
8const LG2: f64 = 3.999_999_999_940_942e-1;
9const LG3: f64 = 2.857_142_874_366_239e-1;
10const LG4: f64 = 2.222_219_843_214_978_4e-1;
11const LG5: f64 = 1.818_357_216_161_805e-1;
12const LG6: f64 = 1.531_383_769_920_937_3e-1;
13const LG7: f64 = 1.479_819_860_511_658_6e-1;
14
15const EXP_P1: f64 = 1.666_666_666_666_660_2e-1;
16const EXP_P2: f64 = -2.777_777_777_701_559_3e-3;
17const EXP_P3: f64 = 6.613_756_321_437_934e-5;
18const EXP_P4: f64 = -1.653_390_220_546_525_2e-6;
19const EXP_P5: f64 = 4.138_136_797_057_238_5e-8;
20
21/// Returns the largest integer less than or equal to `x`.
22#[must_use]
23#[inline]
24pub fn floor(x: f64) -> f64 {
25    #[cfg(target_arch = "aarch64")]
26    {
27        let out: f64;
28        // SAFETY: `frintm` is a pure scalar floating-point instruction with no memory side effects.
29        unsafe {
30            core::arch::asm!(
31                "frintm {:d}, {:d}",
32                out(vreg) out,
33                in(vreg) x,
34                options(pure, nomem, nostack),
35            );
36        }
37        out
38    }
39    #[cfg(not(target_arch = "aarch64"))]
40    {
41        if x.is_nan() || x.is_infinite() || x == 0.0 {
42            return x;
43        }
44        let t = trunc(x);
45        if x < t { t - 1.0 } else { t }
46    }
47}
48
49/// Returns the smallest integer greater than or equal to `x`.
50#[must_use]
51#[inline]
52pub fn ceil(x: f64) -> f64 {
53    #[cfg(target_arch = "aarch64")]
54    {
55        let out: f64;
56        // SAFETY: `frintp` is a pure scalar floating-point instruction with no memory side effects.
57        unsafe {
58            core::arch::asm!(
59                "frintp {:d}, {:d}",
60                out(vreg) out,
61                in(vreg) x,
62                options(pure, nomem, nostack),
63            );
64        }
65        out
66    }
67    #[cfg(not(target_arch = "aarch64"))]
68    {
69        if x.is_nan() || x.is_infinite() || x == 0.0 {
70            return x;
71        }
72        let t = trunc(x);
73        if x > t { t + 1.0 } else { t }
74    }
75}
76
77/// Returns the integer part of `x`, rounding toward zero.
78#[must_use]
79#[inline]
80pub fn trunc(x: f64) -> f64 {
81    #[cfg(target_arch = "aarch64")]
82    {
83        let out: f64;
84        // SAFETY: `frintz` is a pure scalar floating-point instruction with no memory side effects.
85        unsafe {
86            core::arch::asm!(
87                "frintz {:d}, {:d}",
88                out(vreg) out,
89                in(vreg) x,
90                options(pure, nomem, nostack),
91            );
92        }
93        out
94    }
95    #[cfg(not(target_arch = "aarch64"))]
96    {
97        let bits = x.to_bits();
98        let exp = ((bits >> 52) & 0x7ff) as i32 - 1023;
99        if exp < 0 {
100            return f64::from_bits(bits & (1u64 << 63));
101        }
102        if exp >= 52 {
103            return x;
104        }
105        let mask = (1u64 << (52 - exp)) - 1;
106        f64::from_bits(bits & !mask)
107    }
108}
109
110/// Computes the natural logarithm $\ln(x)$ using the FDLIBM minimax approximation.
111#[must_use]
112pub fn ln(x: f64) -> f64 {
113    if x.is_nan() || x < 0.0 {
114        return f64::NAN;
115    }
116    if x == 0.0 {
117        return f64::NEG_INFINITY;
118    }
119    if x == f64::INFINITY {
120        return f64::INFINITY;
121    }
122    if x == 1.0 {
123        return 0.0;
124    }
125
126    let mut ux = x.to_bits();
127    let mut k = 0i32;
128    if (ux >> 52) == 0 {
129        // Subnormal input: scale up by 2^52.
130        ux = (x * ((1u64 << 52) as f64)).to_bits();
131        k -= 52;
132    }
133
134    k += ((ux >> 52) as i32) - 1023;
135    let mant_hi = ((ux >> 32) as u32) & 0x000f_ffff;
136    // Center reduced mantissa around [sqrt(2)/2, sqrt(2)].
137    let offset = (mant_hi + 0x95f64) & 0x0010_0000;
138    let m_bits = (ux & 0x000f_ffff_ffff_ffff) | (((offset ^ 0x3ff0_0000) as u64) << 32);
139    k += (offset >> 20) as i32;
140
141    let f = f64::from_bits(m_bits) - 1.0;
142    let s = f / (2.0 + f);
143    let z = s * s;
144    let w = z * z;
145    let t1 = w * (LG2 + w * (LG4 + w * LG6));
146    let t2 = z * (LG1 + w * (LG3 + w * (LG5 + w * LG7)));
147    let r = t2 + t1;
148    let hfsq = 0.5 * f * f;
149    let dk = k as f64;
150
151    dk * LN2_HI - ((hfsq - (s * (hfsq + r) + dk * LN2_LO)) - f)
152}
153
154/// Computes $e^x$ using the FDLIBM range reduction and Remez rational approximation.
155fn exp(x: f64) -> f64 {
156    if x.is_nan() {
157        return f64::NAN;
158    }
159    if x > 709.782_712_893_384 {
160        return f64::INFINITY;
161    }
162    if x < -745.133_219_101_941_1 {
163        return 0.0;
164    }
165    if x == 0.0 {
166        return 1.0;
167    }
168
169    let k = if x >= 0.0 {
170        floor(x * INV_LN2 + 0.5) as i32
171    } else {
172        ceil(x * INV_LN2 - 0.5) as i32
173    };
174    let dk = k as f64;
175    let hi = x - dk * LN2_HI;
176    let lo = dk * LN2_LO;
177    let r = hi - lo;
178    let z = r * r;
179    let c = r - z * (EXP_P1 + z * (EXP_P2 + z * (EXP_P3 + z * (EXP_P4 + z * EXP_P5))));
180    let y = 1.0 - ((lo - (r * c) / (2.0 - c)) - hi);
181
182    scale_pow2(y, k)
183}
184
185#[inline]
186fn scale_pow2(y: f64, k: i32) -> f64 {
187    if (-1021..=1023).contains(&k) {
188        return y * f64::from_bits(((k + 1023) as u64) << 52);
189    }
190    if k == 1024 {
191        return (y * f64::from_bits(2046u64 << 52)) * 2.0;
192    }
193    // Subnormal range (k < -1021): scale in two steps.
194    let k1 = -1022;
195    let k2 = k - k1;
196    (y * f64::from_bits(((k1 + 1023) as u64) << 52)) * f64::from_bits(((k2 + 1023) as u64) << 52)
197}
198
199/// classifies finite `y`: `0` = non-integer, `1` = odd integer, `2` = even integer.
200#[inline]
201fn classify_integer(y: f64) -> u8 {
202    let ay = if y < 0.0 { -y } else { y };
203    if ay >= 9_007_199_254_740_992.0 {
204        // |y| >= 2^53: all representable IEEE-754 f64 values are even integers.
205        return 2;
206    }
207    let t = trunc(ay);
208    if t != ay {
209        return 0;
210    }
211    let n = t as u64;
212    if (n & 1) == 1 { 1 } else { 2 }
213}
214
215#[inline]
216fn powi_small(mut base: f64, exp_val: i32) -> f64 {
217    let mut e = if exp_val < 0 {
218        base = 1.0 / base;
219        (-exp_val) as u32
220    } else {
221        exp_val as u32
222    };
223    let mut acc = 1.0;
224    while e != 0 {
225        if (e & 1) != 0 {
226            acc *= base;
227        }
228        e >>= 1;
229        if e != 0 {
230            base *= base;
231        }
232    }
233    acc
234}
235
236/// Computes $x^y$ following IEEE-754 special-case rules.
237#[must_use]
238pub fn powf(x: f64, y: f64) -> f64 {
239    if y == 0.0 || x == 1.0 {
240        return 1.0;
241    }
242    if x.is_nan() || y.is_nan() {
243        return f64::NAN;
244    }
245
246    if y.is_infinite() {
247        let ax = if x < 0.0 { -x } else { x };
248        if ax == 1.0 {
249            return 1.0;
250        }
251        return if (ax > 1.0) == (y > 0.0) {
252            f64::INFINITY
253        } else {
254            0.0
255        };
256    }
257
258    let y_int = classify_integer(y);
259
260    if x.is_infinite() {
261        if x > 0.0 {
262            return if y > 0.0 { f64::INFINITY } else { 0.0 };
263        }
264        return if y > 0.0 {
265            if y_int == 1 {
266                f64::NEG_INFINITY
267            } else {
268                f64::INFINITY
269            }
270        } else if y_int == 1 {
271            -0.0
272        } else {
273            0.0
274        };
275    }
276
277    if x == 0.0 {
278        let neg_zero = (x.to_bits() >> 63) != 0;
279        return if y > 0.0 {
280            if neg_zero && y_int == 1 { -0.0 } else { 0.0 }
281        } else if neg_zero && y_int == 1 {
282            f64::NEG_INFINITY
283        } else {
284            f64::INFINITY
285        };
286    }
287
288    let mut sign = 1.0;
289    let ax = if x < 0.0 {
290        if y_int == 0 {
291            return f64::NAN;
292        }
293        if y_int == 1 {
294            sign = -1.0;
295        }
296        -x
297    } else {
298        x
299    };
300
301    if y_int != 0 && (-64.0..=64.0).contains(&y) {
302        return sign * powi_small(ax, y as i32);
303    }
304
305    sign * exp(y * ln(ax))
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    fn rel_err(actual: f64, expected: f64) -> f64 {
313        let diff = if actual >= expected {
314            actual - expected
315        } else {
316            expected - actual
317        };
318        diff / (if expected >= 0.0 { expected } else { -expected })
319    }
320
321    #[test]
322    fn rounding_and_sqrt_exact_and_edge_cases() {
323        assert_eq!(floor(2.7), 2.0);
324        assert_eq!(floor(-2.7), -3.0);
325        assert_eq!(floor(3.0), 3.0);
326        assert_eq!(floor(-3.0), -3.0);
327        assert_eq!(floor(0.0).to_bits(), 0.0f64.to_bits());
328        assert_eq!(floor(-0.0).to_bits(), (-0.0f64).to_bits());
329        assert!(floor(f64::NAN).is_nan());
330        assert_eq!(floor(f64::INFINITY), f64::INFINITY);
331        assert_eq!(floor(f64::NEG_INFINITY), f64::NEG_INFINITY);
332
333        assert_eq!(ceil(2.3), 3.0);
334        assert_eq!(ceil(-2.3), -2.0);
335        assert_eq!(ceil(4.0), 4.0);
336        assert_eq!(ceil(-4.0), -4.0);
337        assert_eq!(ceil(-0.0).to_bits(), (-0.0f64).to_bits());
338        assert!(ceil(f64::NAN).is_nan());
339
340        assert_eq!(trunc(2.9), 2.0);
341        assert_eq!(trunc(-2.9), -2.0);
342        assert_eq!(trunc(-0.5).to_bits(), (-0.0f64).to_bits());
343        assert!(trunc(f64::NAN).is_nan());
344    }
345
346    #[test]
347    fn ln_exp_powf_accuracy_and_ieee_special_cases() {
348        assert_eq!(ln(1.0), 0.0);
349        assert_eq!(ln(0.0), f64::NEG_INFINITY);
350        assert_eq!(ln(-0.0), f64::NEG_INFINITY);
351        assert!(ln(-1.0).is_nan());
352        assert!(ln(f64::NAN).is_nan());
353        assert_eq!(ln(f64::INFINITY), f64::INFINITY);
354
355        assert!(rel_err(ln(core::f64::consts::E), 1.0) < 1e-15);
356        assert!(rel_err(ln(2.0), core::f64::consts::LN_2) < 1e-15);
357        assert!(rel_err(ln(10.0), core::f64::consts::LN_10) < 1e-15);
358        assert!(rel_err(ln(0.5), -core::f64::consts::LN_2) < 1e-15);
359
360        assert_eq!(exp(0.0), 1.0);
361        assert_eq!(exp(800.0), f64::INFINITY);
362        assert_eq!(exp(-800.0), 0.0);
363        assert!(exp(f64::NAN).is_nan());
364        assert!(rel_err(exp(1.0), core::f64::consts::E) < 1e-15);
365        assert!(rel_err(exp(core::f64::consts::LN_2 * 10.0), 1024.0) < 1e-14);
366
367        assert_eq!(powf(2.0, 10.0), 1024.0);
368        assert_eq!(powf(-2.0, 3.0), -8.0);
369        assert_eq!(powf(-2.0, 4.0), 16.0);
370        assert!(powf(-2.0, 0.5).is_nan());
371        assert_eq!(powf(f64::NAN, 0.0), 1.0);
372        assert_eq!(powf(1.0, f64::NAN), 1.0);
373        assert_eq!(powf(1.0, f64::INFINITY), 1.0);
374        assert_eq!(powf(-1.0, f64::INFINITY), 1.0);
375        assert_eq!(powf(0.0, 3.0).to_bits(), 0.0f64.to_bits());
376        assert_eq!(powf(-0.0, 3.0).to_bits(), (-0.0f64).to_bits());
377        assert_eq!(powf(-0.0, 4.0).to_bits(), 0.0f64.to_bits());
378        assert_eq!(powf(0.0, -2.0), f64::INFINITY);
379        assert_eq!(powf(-0.0, -3.0), f64::NEG_INFINITY);
380        assert!(rel_err(powf(9.0, 0.5), 3.0) < 1e-14);
381        assert!(rel_err(powf(core::f64::consts::E, 2.5), exp(2.5)) < 1e-14);
382    }
383}