const_soft_float/soft_f32/
cos.rs

1/* origin: FreeBSD /usr/src/lib/msun/src/s_cosf.c */
2/*
3 * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
4 * 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 core::f64::consts::FRAC_PI_2;
18
19use crate::soft_f64::SoftF64;
20
21use super::{
22    helpers::{k_cosf, k_sinf, rem_pio2f},
23    SoftF32,
24};
25
26/* Small multiples of pi/2 rounded to double precision. */
27const C1_PIO2: SoftF64 = SoftF64(1.).mul(SoftF64(FRAC_PI_2)); /* 0x3FF921FB, 0x54442D18 */
28const C2_PIO2: SoftF64 = SoftF64(2.).mul(SoftF64(FRAC_PI_2)); /* 0x400921FB, 0x54442D18 */
29const C3_PIO2: SoftF64 = SoftF64(3.).mul(SoftF64(FRAC_PI_2)); /* 0x4012D97C, 0x7F3321D2 */
30const C4_PIO2: SoftF64 = SoftF64(4.).mul(SoftF64(FRAC_PI_2)); /* 0x401921FB, 0x54442D18 */
31
32pub const fn cos(x: SoftF32) -> SoftF32 {
33    let x64 = SoftF64(x.0 as f64);
34
35    let x1p120 = SoftF32::from_bits(0x7b800000); // 0x1p120f === 2 ^ 120
36
37    let mut ix = x.to_bits();
38    let sign = (ix >> 31) != 0;
39    ix &= 0x7fffffff;
40
41    if ix <= 0x3f490fda {
42        /* |x| ~<= pi/4 */
43        if ix < 0x39800000 {
44            /* |x| < 2**-12 */
45            /* raise inexact if x != 0 */
46            let _ = x.add(x1p120);
47            return SoftF32(1.0);
48        }
49        return k_cosf(x64);
50    }
51    if ix <= 0x407b53d1 {
52        /* |x| ~<= 5*pi/4 */
53        if ix > 0x4016cbe3 {
54            /* |x|  ~> 3*pi/4 */
55            return k_cosf(if sign {
56                x64.add(C2_PIO2)
57            } else {
58                x64.sub(C2_PIO2)
59            })
60            .neg();
61        } else if sign {
62            return k_sinf(x64.add(C1_PIO2));
63        } else {
64            return k_sinf(C1_PIO2.sub(x64));
65        }
66    }
67    if ix <= 0x40e231d5 {
68        /* |x| ~<= 9*pi/4 */
69        if ix > 0x40afeddf {
70            /* |x| ~> 7*pi/4 */
71            return k_cosf(if sign {
72                x64.add(C4_PIO2)
73            } else {
74                x64.sub(C4_PIO2)
75            });
76        } else if sign {
77            return k_sinf(x64.neg().sub(C3_PIO2));
78        } else {
79            return k_sinf(x64.sub(C3_PIO2));
80        }
81    }
82
83    /* cos(Inf or NaN) is NaN */
84    if ix >= 0x7f800000 {
85        return x.sub(x);
86    }
87
88    /* general argument reduction needed */
89    let (n, y) = rem_pio2f(x);
90    match n & 3 {
91        0 => k_cosf(y),
92        1 => k_sinf(y.neg()),
93        2 => k_cosf(y).neg(),
94        _ => k_sinf(y),
95    }
96}