gpt4 book ai didi

java - 计算 sin(x) w/oMath 并仅在 java 中使用循环

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:08:28 24 4
gpt4 key购买 nike

我必须使用泰勒级数计算 Math.sin(x):

n

∑ (-1)^i* (x^(2i+1) / (2i+1)!) for n → ∞

i=0

因此,我只能使用循环(不能递归),不能使用 Math 类。这是我走了多远:

public double sinLoops(double x) {
int potenz1;
double potenz2 = x;
double fac = 1;
double result = 0;

do {
if ((i % 2) == 0) {
potenz1 = 1;
} else {
potenz1 = (-1);
}

for (int counter = 1; counter < (2 * i + 1); counter++) {
potenz2 *= x;
}
for (int counter2 = (2 * i + 1); counter2 >= 1; counter2--) {
fac *= counter2;
}
result += potenz1 * potenz2 / fac;
i++;
} while (result > 0.0000001 || result < -0.0000001);
return result;
}

但是,我认为我的中断条件不太正确(-1*10^-7 或 1*10^-7),返回的结果是 NaN。我已经查过了,但我现在有点过度挑战,所以我希望有人能帮助我解决这个问题。 :)

提前致谢!

最佳答案

  1. 你没有初始化 i。
  2. 您根据结果而不是总和的泰勒元素检查了最终条件。
  3. 您离开 potenz2 和 fac 元素是为了让螺旋不受控制,而不是为系列中的每个新元素重置它们。
  4. 最终他们会达到无穷大和无穷大,将它们相除并得到 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;
}

关于java - 计算 sin(x) w/oMath 并仅在 java 中使用循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40699425/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com