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