Java 莱布尼兹级数回路不收敛

Java 莱布尼兹级数回路不收敛,java,loops,Java,Loops,所以我决定试用莱布尼兹级数PI估计器 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

所以我决定试用莱布尼兹级数PI估计器

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);
       }
    }
}

我的问题: 为什么输出没有收敛到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);

试试这个

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);


这很有效,我测试过了:

for (int i=1; i < n; i++) {
    double calculations = Math.pow(-1,i) / (2 * i + 1);
    sum += calculations;
    System.out.println((sum + 1) * 4);
}

这很有效,我测试过了:

for (int i=1; i < n; i++) {
    double calculations = Math.pow(-1,i) / (2 * i + 1);
    sum += calculations;
    System.out.println((sum + 1) * 4);
}

看起来你的代码运行得很好,但它进入了2.6666的范围;我希望它总是在一个3。不过,你的答案很清楚!第一次迭代总是2.6666。这就是算法的本质。我将最终答案移到循环之外,这样您就不会得到所有的迭代。但我的算法是正确的。我还解释了你的错误。这为我澄清了问题,谢谢,我会接受你的回答,因为它100%回答了我的问题!我无意中接受了你的答案,现在它被重新接受了。看起来你的代码运行得很好,但它进入了2.6666的范围;我希望它总是在一个3。不过,你的答案很清楚!第一次迭代总是2.6666。这就是算法的本质。我将最终答案移到循环之外,这样您就不会得到所有的迭代。但我的算法是正确的。我还解释了你的错误。这为我澄清了问题,谢谢,我会接受你的回答,因为它100%回答了我的问题!我无意中没有接受你的答案,现在是了reaccepted@Jackov经过多次运行后,我发现它确实工作得很好,我只是限制了循环的数量!但是你的答案只是告诉我它是有效的,但是如果你看看@WJS answer,它会告诉我算法的另一种工作方式@Jackov Kusic在多次运行后,我发现它确实工作得很好,我只是限制了循环的数量!但是你的答案只是告诉我它是有效的,但是如果你看看@WJS answer,它会告诉我算法的另一种工作方式!