>你没有初始化我.
>您检查了结果的最终条件,而不是总和的taylor元素.
>你留下了potenz2和fac元素来保持螺旋失控,而不是为系列中的每个新元素重置它们.
>最终他们会达到无限和无限,划分并获得NaN.添加到运行结果的NaN是NaN,并且实际上为条件返回true并退出循环(NaN与条件有奇数效果).
这是工作代码,对问题进行评论.
public double sinLoops(double x) {
int i = 0; //this didn't exist.
double result = 0;
double seriesElement; //You need the individual taylor series element.
do {
double potenz2 = x; //these need to be reset each time.
double fac = 1; //if not they overflow and infinity/infinity is NaN and it exits.
int potenz1 = ((i & 1) == 1) ? -1 : 1; //this is just short hand.
for (int counter = 1; counter < (2 * i + 1); counter++) {
potenz2 *= x;
}
for (int counter2 = (2 * i + 1); counter2 >= 1; counter2--) {
fac *= counter2; //we could actually keep the last iteration and do 2*(i-1)+1 to 2*i+1 each new i.
}
seriesElement = potenz1 * potenz2 / fac; //we need to save the value here.
result += seriesElement; //we are summing them in the results.
i++;
} while (seriesElement > 0.0000001 || seriesElement < -0.0000001); //We check this conditional against the series element, *NOT THE RESULT*
return result;
}
如果有人以某种方式需要这种方式来进行某种生产工作,速度是关键的(而且错误的答案是错误的,尽管在这种情况下使用数学),而不是“我可以为我做功课”,这里是优化的代码:
public double sinLoops(double x) {
double result = 0, powerx = -1, fac = 1;
int i = 0, n, m = 0;
while (true) {
n = m;
m = (i++*2) + 1;
powerx *= -1;
while (n < m) {
powerx *= x;
fac *= ++n;
}
if ((Double.isInfinite(fac)) || (Double.isInfinite(powerx))) break;
result += powerx / fac;
}
return result;
}