简体   繁体   English

Java:对Wallis产品进行编码以找到pi

[英]Java: coding the Wallis product to find pi

I am trying to write a code to output pi using the Wallis product formula: https://en.wikipedia.org/wiki/Wallis_product 我正在尝试使用Wallis产品公式编写代码以输出pi: https : //en.wikipedia.org/wiki/Wallis_product

This is my code: 这是我的代码:

public class PI {
    public static void main(String[] args) {
      pI();
    }

    public static void pI () {

    double pi = 0;
    int a = 0;
    int b = 1;
    double denom = 0;
    double num = 0;
    int temp = 0;
    int count = 0;
    double halfpi = 1;


        while(true) {
          temp = b;
          b = temp + 2;
          denom = temp*b;

          a += 2;
          num = a*a; 

          halfpi *= (num/denom);
          count++;

          System.out.println(halfpi*2);                    
        }    
    }
}

I have found that the code works just fine until the loop exceeds around 33000 iterations. 我发现代码可以正常工作,直到循环超过33000次迭代为止。 After this point it just prints: "-0.0": 在此之后,它仅打印:“ -0.0”:

-0.0
-0.0
-0.0
-0.0
-0.0
...

----jGRASP: process ended by user.

What could be causing this? 是什么原因造成的?

redFIVE is right. redFIVE是正确的。 You are mixing int and double which causes problems. 您正在混合int和double导致问题。 This would fix it 这会解决它

public class PI {
    public static void main(String[] args) {
      pI();
    }

    public static void pI () {

    double pi = 0;
    double a = 0;
    double b = 1;
    double denom = 0;
    double num = 0;
    double temp = 0;
    double count = 0;
    double halfpi = 1;


        while(true) {
          temp = b;
          b = temp + 2;
          denom = temp*b;

          a += 2;
          num = a*a; 

          halfpi *= (num/denom);
          count++;

          System.out.println(halfpi*2);                    
        }    
    }
}

The issue is because you are mixing INT's and Doubles. 问题是因为您混合使用INT和Doubles。 Your code will not produce any errors because this type of multiplication is fine however when you are assigning ints and then trying to assign them back to doubles you are losing everything except for the integer value before the decimal. 您的代码不会产生任何错误,因为这种类型的乘法很好,但是,当您分配int然后尝试将它们重新分配为double时,您将丢失除小数点前的整数值以外的所有内容。

double pi = 0;
double a = 0;
double b = 1;
double denom = 0;
double num = 0;
double temp = 0;
double count = 0;
double halfpi = 1;

The ints are restricting the capablility to get all the decimal points so fixing it should work. 整数限制了获取所有小数点的功能,因此修复它应该可以。 Also you will run out of heap space very quickly with this program. 另外,使用此程序会很快耗尽堆空间。 Just saying 只是说

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM