1 // origin: FreeBSD /usr/src/lib/msun/src/s_cos.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 use super::{k_cos, k_sin, rem_pio2};
13 
14 // cos(x)
15 // Return cosine function of x.
16 //
17 // kernel function:
18 //      k_sin           ... sine function on [-pi/4,pi/4]
19 //      k_cos           ... cosine function on [-pi/4,pi/4]
20 //      rem_pio2        ... argument reduction routine
21 //
22 // Method.
23 //      Let S,C and T denote the sin, cos and tan respectively on
24 //      [-PI/4, +PI/4]. Reduce the argument x to y1+y2 = x-k*pi/2
25 //      in [-pi/4 , +pi/4], and let n = k mod 4.
26 //      We have
27 //
28 //          n        sin(x)      cos(x)        tan(x)
29 //     ----------------------------------------------------------
30 //          0          S           C             T
31 //          1          C          -S            -1/T
32 //          2         -S          -C             T
33 //          3         -C           S            -1/T
34 //     ----------------------------------------------------------
35 //
36 // Special cases:
37 //      Let trig be any of sin, cos, or tan.
38 //      trig(+-INF)  is NaN, with signals;
39 //      trig(NaN)    is that NaN;
40 //
41 // Accuracy:
42 //      TRIG(x) returns trig(x) nearly rounded
43 //
44 #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
cos(x: f64) -> f6445 pub fn cos(x: f64) -> f64 {
46     let ix = (f64::to_bits(x) >> 32) as u32 & 0x7fffffff;
47 
48     /* |x| ~< pi/4 */
49     if ix <= 0x3fe921fb {
50         if ix < 0x3e46a09e {
51             /* if x < 2**-27 * sqrt(2) */
52             /* raise inexact if x != 0 */
53             if x as i32 == 0 {
54                 return 1.0;
55             }
56         }
57         return k_cos(x, 0.0);
58     }
59 
60     /* cos(Inf or NaN) is NaN */
61     if ix >= 0x7ff00000 {
62         return x - x;
63     }
64 
65     /* argument reduction needed */
66     let (n, y0, y1) = rem_pio2(x);
67     match n & 3 {
68         0 => k_cos(y0, y1),
69         1 => -k_sin(y0, y1, 1),
70         2 => -k_cos(y0, y1),
71         _ => k_sin(y0, y1, 1),
72     }
73 }
74