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

>你没有初始化我.

>您检查了结果的最终条件,而不是总和的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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值