在Java中创建自定义的Sin()函数

Don*_*e H 2 java trigonometry

我必须在Comp Sci类中从头开始创建sin函数,我正在接近解决方案.但是,我仍然遇到一些问题.如果我输入的值为.5PI或更低,它可以工作,但否则我得到的结果不正确.这是我到目前为止的代码:

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++;
}
Run Code Online (Sandbox Code Playgroud)

Lui*_*kal 5

就像Federico指出的那样,问题可能出在你的factorial()或pow()中.我运行了一个测试,它可以用Math类中提供的pow()函数替换你的函数,并且这个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);
} 
Run Code Online (Sandbox Code Playgroud)