1 | // origin: FreeBSD /usr/src/lib/msun/src/s_sin.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 | // sin(x) |
15 | // Return sine function of x. |
16 | // |
17 | // kernel function: |
18 | // k_sin ... sine function on [-pi/4,pi/4] |
19 | // k_cos ... cose 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 | #[cfg_attr (all(test, assert_no_panic), no_panic::no_panic)] |
44 | pub fn sin(x: f64) -> f64 { |
45 | let x1p120 = f64::from_bits(0x4770000000000000); // 0x1p120f === 2 ^ 120 |
46 | |
47 | /* High word of x. */ |
48 | let ix = (f64::to_bits(x) >> 32) as u32 & 0x7fffffff; |
49 | |
50 | /* |x| ~< pi/4 */ |
51 | if ix <= 0x3fe921fb { |
52 | if ix < 0x3e500000 { |
53 | /* |x| < 2**-26 */ |
54 | /* raise inexact if x != 0 and underflow if subnormal*/ |
55 | if ix < 0x00100000 { |
56 | force_eval!(x / x1p120); |
57 | } else { |
58 | force_eval!(x + x1p120); |
59 | } |
60 | return x; |
61 | } |
62 | return k_sin(x, 0.0, 0); |
63 | } |
64 | |
65 | /* sin(Inf or NaN) is NaN */ |
66 | if ix >= 0x7ff00000 { |
67 | return x - x; |
68 | } |
69 | |
70 | /* argument reduction needed */ |
71 | let (n, y0, y1) = rem_pio2(x); |
72 | match n & 3 { |
73 | 0 => k_sin(y0, y1, 1), |
74 | 1 => k_cos(y0, y1), |
75 | 2 => -k_sin(y0, y1, 1), |
76 | _ => -k_cos(y0, y1), |
77 | } |
78 | } |
79 | |
80 | #[test ] |
81 | fn test_near_pi() { |
82 | let x: f64 = f64::from_bits(0x400921fb000FD5DD); // 3.141592026217707 |
83 | let sx: f64 = f64::from_bits(0x3ea50d15ced1a4a2); // 6.273720864039205e-7 |
84 | let result: f64 = sin(x); |
85 | #[cfg (all(target_arch = "x86" , not(target_feature = "sse2" )))] |
86 | let result = force_eval!(result); |
87 | assert_eq!(result, sx); |
88 | } |
89 | |