Skip to main content

libm/math/
rem_pio2f.rs

1/* origin: FreeBSD /usr/src/lib/msun/src/e_rem_pio2f.c */
2/*
3 * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
4 * Debugged and optimized by Bruce D. Evans.
5 */
6/*
7 * ====================================================
8 * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
9 *
10 * Developed at SunPro, a Sun Microsystems, Inc. business.
11 * Permission to use, copy, modify, and distribute this
12 * software is freely granted, provided that this notice
13 * is preserved.
14 * ====================================================
15 */
16
17use super::rem_pio2_large;
18
19const TOINT: f64 = 1.5 / f64::EPSILON;
20
21/// 53 bits of 2/pi
22const INV_PIO2: f64 = 6.36619772367581382433e-01; /* 0x3FE45F30, 0x6DC9C883 */
23/// first 25 bits of pi/2
24const PIO2_1: f64 = 1.57079631090164184570e+00; /* 0x3FF921FB, 0x50000000 */
25/// pi/2 - pio2_1
26const PIO2_1T: f64 = 1.58932547735281966916e-08; /* 0x3E5110b4, 0x611A6263 */
27
28/// Return the remainder of x rem pi/2 in *y
29///
30/// use double precision for everything except passing x
31/// use __rem_pio2_large() for large x
32#[cfg_attr(assert_no_panic, no_panic::no_panic)]
33pub(crate) fn rem_pio2f(x: f32) -> (i32, f64) {
34    let x64 = x as f64;
35
36    let mut tx: [f64; 1] = [0.];
37    let mut ty: [f64; 1] = [0.];
38
39    let ix = x.to_bits() & 0x7fffffff;
40    /* 25+53 bit pi is good enough for medium size */
41    if ix < 0x4dc90fdb {
42        /* |x| ~< 2^28*(pi/2), medium size */
43        /* Use a specialized rint() to get fn.  Assume round-to-nearest. */
44        let tmp = x64 * INV_PIO2 + TOINT;
45        // force rounding of tmp to it's storage format on x87 to avoid
46        // excess precision issues.
47        #[cfg(all(target_arch = "x86", not(target_feature = "sse2")))]
48        let tmp = force_eval!(tmp);
49        let f_n = tmp - TOINT;
50        return (f_n as i32, x64 - f_n * PIO2_1 - f_n * PIO2_1T);
51    }
52    if ix >= 0x7f800000 {
53        /* x is inf or NaN */
54        return (0, x64 - x64);
55    }
56    /* scale x into [2^23, 2^24-1] */
57    let sign = (x.to_bits() >> 31) != 0;
58    let e0 = ((ix >> 23) - (0x7f + 23)) as i32; /* e0 = ilogb(|x|)-23, positive */
59    tx[0] = f32::from_bits(ix - (e0 << 23) as u32) as f64;
60    let n = rem_pio2_large(&tx, &mut ty, e0, 0);
61    if sign {
62        return (-n, -ty[0]);
63    }
64    (n, ty[0])
65}