user236501 user236501 - 4 months ago 19
Java Question

How to re-implement sin() method in Java ? (to have results close to Math.sin() )

I know Math.sin() can work but I need to implement it myself using factorial(int) i have a factorial method already below are my sin method but i can't get the same result as

Math.sin()
:

public static double factorial(double n) {
if (n <= 1) // base case
return 1;
else
return n * factorial(n - 1);
}

public static double sin(int n) {
double sum = 0.0;
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
sum += Math.pow(1, i) / factorial(2 * i + 1);
} else {
sum += Math.pow(-1, i) / factorial(2 * i + 1);
}
}
return sum;
}

Answer

You should use the Taylor series. A great tutorial here

I can see that you've tried but your sin method is incorrect


public static sin(int n) {
    // angle to radians
    double rad = n*1./180.*Math.PI;
    // the first element of the taylor series
    double sum = rad;
    // add them up until a certain precision (eg. 10)
    for (int i = 1; i <= PRECISION; i++) {
        if (i % 2 == 0) 
            sum += Math.pow(rad, 2*i+1) / factorial(2 * i + 1);
        else 
            sum -= Math.pow(rad, 2*i+1) / factorial(2 * i + 1);
    }
    return sum;
}

A working example of calculating the sin function. Sorry I've jotted it down in C++, but hope you get the picture. It's not that different :)