Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 800
user236501 Avatar asked Dec 13 '22 12:12

user236501


2 Answers

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 :)

like image 153
Matyas Avatar answered Dec 15 '22 00:12

Matyas


Your formula is wrong and you are getting a rough result of sin(1) and all you're doing by changing n is changing the accuracy of this calculation. You should look the formula up in Wikipedia and there you'll see that your n is in the wrong place and shouldn't be used as the limit of the for loop but rather in the numerator of the fraction, in the Math.pow(...) method. Check out Taylor Series

like image 31
Hovercraft Full Of Eels Avatar answered Dec 15 '22 00:12

Hovercraft Full Of Eels