【发布时间】:2015-01-29 17:24:32
【问题描述】:
我用 Java 写了一个正弦函数,它应该像计算 x 的正弦一样
我的函数看起来像
public static double sine(int x) {
double result = 0;
for(int n = 0; n <= 8; n++) {
double temp = 2 * n + 1;
result += Math.pow(-1, n) * Math.pow(x, temp) / fact(temp); // fact() calculates faculty
}
return result;
}
只有几个小数位与 Math.sin() 匹配,但前提是 x 小于 6 并且 n 的限制等于 8。
有时,如果 x 大于 6,sine() 甚至返回 4.106,或者如果 n 的限制大于 32,它返回 NaN 或 -Infinity...
我做错了什么?
希望您能帮助我并提前致谢!
【问题讨论】:
-
B-b-b-b-b-b-b-BUFFER OVERFLOW!!!1!(好吧,从技术上讲是整数溢出,但这听起来不像 wrestl-ize 有趣)
-
尝试使用
BigIntegers。 -
@JackManey:真正的问题似乎是 x 太大,泰勒公式无法很好地收敛。
-
为什么您的
sine方法采用int? -
用霍纳形式评估这个多项式而不是依赖
Math.pow和你的fact可能是有利可图的。
标签: java function math trigonometry