[英]Leibniz series Loop not converging
所以我决定试用莱布尼茨系列(PI ESTIMATOR)
PI/4 = 1/3 - 1/5 + 1/7 - 1/9 + 1/11 etc...
这是我的代码:
import java.util.Scanner;
public class PIEstimator{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of Iterations:");
int n = sc.nextInt();
double sum = 0;
//START OF Leibniz series
for (int i=1; i < n; i++) {
double calculations = Math.pow(-1,i + 1) / (2 * i + 1);
sum = sum += calculations;
System.out.println(sum + 3);
}
}
}
如果n = 12
,这是我的输出
3.3333333333333335
3.1333333333333333
3.276190476190476
3.165079365079365
3.255988455988456
3.179065379065379
3.2457320457320455
3.186908516320281
3.2395400952676496
3.1919210476486017
3.235399308518167
为什么输出没有收敛到 3.14159265......?
我的数学不正确吗?
比你提前!
尝试这个。
for (int i=1; i < n; i++) {
double calculations = Math.pow(-1,i + 1) / (2 * (i-1) + 1);
sum += calculations;
}
System.out.println(4*sum);
2*(i-1) + 1 = 0 + 1 = 1.
pi/4
所以你需要乘以4
。 这是一个建议。 无需执行 Math.pow 开销,只需使用三元运算符 ( ?:
:) 来查看i
是偶数还是奇数并相应地更改符号。
double calculations = ((i % 2) == 0 ? -1. : 1.) / (2.*(i-1)+1);
这工作正常(我测试过):
for (int i=1; i < n; i++) {
double calculations = Math.pow(-1,i) / (2 * i + 1);
sum += calculations;
System.out.println((sum + 1) * 4);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.