[英]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. 我必须在Comp Sci类中从头开始创建sin函数,我正在接近解决方案。 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. 如果我输入的值为.5PI或更低,它可以工作,但否则我得到的结果不正确。 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(). 就像Federico指出的那样,问题可能出在你的factorial()或pow()中。 I ran a test that worked fine replacing your functions with the pow() function provided in the Math class, and this factorial(): 我运行了一个测试,它可以用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);
}
Some advices: 一些建议:
EDIT. 编辑。 Suggestion: once you have computed the k-th term, you can compute the (k+1)-th one by: 建议:一旦计算了第k个项,就可以通过以下方式计算第(k + 1)项:
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. 对于0 - 1 / 2PI之外的值,它们都可以从范围内的值计算。
// 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.