I wrote a sine function in Java, that should calculate the sine of x like
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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…