gpt4 book ai didi

java - 使用莱布尼茨级数求 pi 值

转载 作者:行者123 更新时间:2023-11-30 07:39:54 25 4
gpt4 key购买 nike

我开始学习 Java,但我的代码有问题。

当然它有明显的错误:它无法运行。我被要求使用莱布尼兹级数找到 pi 值,以及达到六位有效数字 (3.141592) 的迭代次数。

到目前为止我有这个:

public class Findingpie2 {
public static void main(String[] args) {
double pi = 0.0;
int counter = 1;
for (int n = 0; n < counter; n++) {
pi += Math.pow(-1, n) / (2*n + 1);
counter++;
if (pi==3.141592) {
System.out.println("the value of pi is: "+String.format("%6f",4*pi));
System.out.println("the number of iterations for pi value is "+n);
}
}
}
}

最佳答案

仅使用容差标准,显示结果而不进行任何舍入:

package dummy;

import static java.lang.String.format;
import static java.lang.System.out;

import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Map.Entry;

/*
* Finding pi value using Leibniz series
*
* The Leibniz series is converging. To compare two successive values
* is enough to get the required precision.
*
* http://stackoverflow.com/questions/34834854/finding-pi-value-using-leibniz-serie
*
*/
public class Findingpie2 {

public static void main(String[] args) {
out.println("Pi, no rounding:");
for (int i = 2; i < 10; i++) {
double tolerance = Math.pow(0.1, i);
Entry<Integer, Double> result = calcpi(tolerance);
String pi = result.getValue().toString().substring(0, i+1);
out.println(format("The value of pi is: %s with %." + i + "f tolerance (%d iterations)." , pi, tolerance, result.getKey()));
}
}

private static Entry<Integer, Double> calcpi(double tolerance) {
int n = 0;
double pi = 0;
double bpi = 10 * tolerance;
double inc = 1;
while (Math.abs(bpi - pi) > tolerance) {
bpi = pi;
pi += inc / (2*n + 1);
inc = -inc;
n++;
}
return new SimpleImmutableEntry<Integer, Double>(n, 4 * pi);
}

}

更新:它将显示:

Pi, no rounding:
The value of pi is: 3.1 with 0,01 tolerance (51 iterations).
The value of pi is: 3.14 with 0,001 tolerance (501 iterations).
The value of pi is: 3.141 with 0,0001 tolerance (5001 iterations).
The value of pi is: 3.1416 with 0,00001 tolerance (50001 iterations).
The value of pi is: 3.14159 with 0,000001 tolerance (500001 iterations).
The value of pi is: 3.141592 with 0,0000001 tolerance (5000001 iterations).
The value of pi is: 3.1415926 with 0,00000001 tolerance (50000001 iterations).
The value of pi is: 3.14159265 with 0,000000001 tolerance (499999987 iterations).

关于java - 使用莱布尼茨级数求 pi 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34834854/

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