Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is sine implemented in Java? [duplicate]

Quick question about the sine function in Java. Does anyone know how the value is computed? I found this question about sin in Java, but that's asking why the sin function isn't wrapped in native code. I'm asking something entirely different. I want to know how the function was implemented. (Since it's wrapped in native code, I can't see it.)

Did they simply implement it from the Taylor series expansion:

sin(x) = x - (x^3)/3! + (x^5)/5! - O(x^7)

I can't look at the code for the Math.sine() function, since it gets wrapped up in native code.

like image 383
Sal Avatar asked Sep 03 '26 04:09

Sal


1 Answers

The implementation can be found here(*).

The sin function is approximated by a 13-degree polynomial. That is, a function on the shape

       c12x12 + c11x11 + ... + c1x1 + c0x0

on the interval [0,π/4]

The description of the algorithm looks as follows:

33 * Algorithm
34 *      1. Since sin(-x) = -sin(x), we need only to consider positive x.
35 *      2. if x < 2^-27 (hx<0x3e400000 0), return x with inexact if x!=0.
36 *      3. sin(x) is approximated by a polynomial of degree 13 on
37 *         [0,pi/4]
38 *                               3            13
39 *              sin(x) ~ x + S1*x + ... + S6*x
40 *         where
41 *
42 *      |sin(x)         2     4     6     8     10     12  |     -58
43 *      |----- - (1+S1*x +S2*x +S3*x +S4*x +S5*x  +S6*x   )| <= 2
44 *      |  x                                               |
45 *
46 *      4. sin(x+y) = sin(x) + sin'(x')*y
47 *                  ~ sin(x) + (1-x*x/2)*y
48 *         For better accuracy, let
49 *                   3      2      2      2      2
50 *              r = x *(S2+x *(S3+x *(S4+x *(S5+x *S6))))
51 *         then                   3    2
52 *              sin(x) = x + (S1*x + (x *(r-y/2)+y))
53 */

(*) Disclamer: Talking about OpenJDK here

like image 74
aioobe Avatar answered Sep 04 '26 18:09

aioobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!