views:

1200

answers:

3

I have to create the sin function from scratch in my Comp Sci class, and I think I got it down. But it still has some problems. If I put in a value of .5PI or less it works. Otherwise it doesn't. Any help would be greatly appreciated.

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++;
}
+2  A: 

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.

Federico Ramponi
+2  A: 

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);
}
Luiz Penkal
A: 

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
}
Bill James