Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

java - Sine calculation with Taylor series not working

I wrote a sine function in Java, that should calculate the sine of x like

wikipedia image

My function looks like

public static double sine(int x) {
    double result = 0;
    for(int n = 0; n <= 8; n++) {
        double temp = 2 * n + 1;
        result += Math.pow(-1, n) * Math.pow(x, temp) / fact(temp); // fact() calculates faculty
        
    }
    return result;
    
}

Only a few decimal places match to Math.sin(), but only if x is smaller then 6 and the limit of n equals to 8.
Sometimes, if x is greater than 6 sine() returns even 4.106 or if limit of n is greater than 32, it returns NaN or -Infinity...
What am I doing wrong?

Hope you can help me and thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With such a low value of n, the Taylor series is a poor approximation of sine for high numbers. For degree 8, any angle higher than around 4 will produce a significantly inaccurate result.

Because sine is periodic, one easy solution would be to modulus divide the angle (in radians) by 2*pi. The StrictMath Class in Java reduces the angle in a different way but the idea is the same. In that case, they reduce the angle to between [-pi/4, pi/4] to improve accuracy. This tool demonstrates how accuracy improves as the degree of the Taylor series increases.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...