简体   繁体   中英

Making a custom Sin() function in Java

I have to create the sin function from scratch in my Comp Sci class, and I am getting close to a solution. However, I am still having a few problems. If I put in a value of .5PI or less it works, but otherwise I get the incorrect result. Here is the code I have so far:

double i=1;
double sinSoFar = 0;
int term = 1;
while(i >= .000001)
{
    i = pow(-1, term + 1) * pow(sinOf, 2*term-1) / factorial(2*term-1);
    sinSoFar=sinSoFar + i;
    term++;
}

Like Federico pointed, the problem probably is in your factorial() or pow(). I ran a test that worked fine replacing your functions with the pow() function provided in the Math class, and this factorial():

public static long factorial(long n) {
        if      (n <  0) throw new RuntimeException("Underflow error in factorial");
        else if (n > 20) throw new RuntimeException("Overflow error in factorial");
        else if (n == 0) return 1;
        else             return n * factorial(n-1);
} 

Some advices:

  • Start with term = 0. The canonical MacLaurin expansion also does
  • compute the powers and the factorial while you are cycling (that is, updating them at each step). Maybe the problem is within pow() or factorial().

EDIT. Suggestion: once you have computed the k-th term, you can compute the (k+1)-th one by:

  • Multiplying by (-1)
  • Multiplying by sinOf^2
  • Dividing by (2k+2)(2k+3)

In this way you can completely avoid the computation of powers and factorials.

As far as values outside of 0 - 1/2PI, they can all be computed from values inside the range.

// First, normalize argument angle (ang) to -PI to PI, 
// by adding/subtracting 2*PI until it's within range
if ( ang > 1/2PI ) {
    sin = sin ( PI - ang );
}
else if ( ang < 0 ) {
    sin = -1 * sin( -1 * ang );
}
else {
    // your original code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM