计算 Pi Java 程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21686036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:04:00  来源:igfitidea点击:

Calculating Pi Java Program

javaoop

提问by sean

I'm taking my first Java programming class and this is my first class project. I'm so confused about how to approach it. Any help or correction will be appreciated.

我正在参加我的第一个 Java 编程课程,这是我的第一个课程项目。我对如何处理它感到非常困惑。任何帮助或更正将不胜感激。

You can approximate the value of the constant PI by using the following series:

您可以使用以下系列来近似计算常数 PI 的值:

PI = 4 ( 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ... + ( (-1)^(i+1) )/ (2i - 1) )

Prompt the user for the value of i (in other words, how many terms in this series to use) to calculate PI. For example, if the user enters 10000, sum the ?rst 10,000 elements of the series and then display the result.

提示用户输入 i 的值(换言之,要使用该系列中的多少项)来计算 PI。例如,如果用户输入 10000,则对系列的前 10,000 个元素求和,然后显示结果。

In addition to displaying the ?nal result (your ?nal approximation of PI), I want you to display along the way your intermediate calculates at every power of 10. So 10, 100, 1000, 10000 and so on, display to the screen the approximation of PI at that number of summed elements.

除了显示最终结果(您对 PI 的最终近似值)之外,我还希望您在中间计算 10 的每个幂的过程中显示。因此,10、100、1000、10000 等,显示在屏幕上在求和元素数处的 PI 近似值。

This is what i did so far ..

这是我到目前为止所做的..

import java.util.Scanner;
        public class CalculatePI {

            public static void main(String[] args) {
                // Create a Scanner object
                Scanner input = new Scanner (System.in);

                // Prompt the user to enter input
                System.out.println("Enter number of terms");
                double i = input.nextDouble(); // value of i user entered
                    double sum = 0;
                for(i=0; i<10000; i++){
                           if(i%2 == 0) // if the remainder of `i/2` is 0
                           sum += -1 / ( 2 * i - 1);
                        else
                           sum += 1 / (2 * i - 1);
    }

                        System.out.println(sum);


    }
}

采纳答案by Sam I am says Reinstate Monica

First thing I see is you attempting to return a value from your void mainmethod.

我看到的第一件事是你试图从你的void main方法中返回一个值。

don't return pi;from your main method. Print it.

不要return pi;从你的主要方法。打印出来。

System.out.println(pi);


Secondly, when people write a forloop, they're commonly iterating over i, which is probably the same ithat your professor referred to in the formula

其次,当人们编写for循环时,他们通常会迭代i,这可能与i您的教授在公式中提到的相同

for(double i=0; i<SomeNumber; i++)
{
    sum += ((-1)^(i+1)) / (2 * i - 1) );
}

now, that won't work correctly as is, you still have to handle the ^, which java doesn't use natively. luckily for you, -1^(i+1)is an alternating number, so you can just use an ifstatement

现在,这将无法正常工作,您仍然必须处理^java 本身不使用的 . 对你-1^(i+1)来说幸运的是,是一个交替的数字,所以你可以使用一个if语句

for(double i=0; i<SomeNumber; i++)
{
    if(i%2 == 0) // if the remainder of `i/2` is 0
        sum += -1 / ( 2 * i - 1);
    else
        sum += 1 / (2 * i - 1);
}

回答by Man I Am

sometimes the answer is a simple line of code. Also you are reassigning i to 0 so Im assuming you are using the user input in the wrong way.

有时答案是一行简单的代码。此外,您将 i 重新分配给 0,因此我假设您以错误的方式使用用户输入。

for(int counter=1;counter<input;counter++){
    sum += Math.pow(-1,counter + 1)/((2*counter) - 1);
}

for input that should can be any variable, hard coded or set by user input (such as 1000, 10000, 100000). This should work

对于可以是任何变量、硬编码或由用户输入设置的输入(例如 1000、10000、100000)。这应该工作

回答by Edmond Weiss

Comprehend the formula: Think about the nature of the formula before attempting to solve by code. I say this because if you did, you wouldn't try to alternate between positive and negative with the following code:

理解公式:在尝试通过代码解决之前先考虑公式的性质。我这样说是因为如果你这样做了,你就不会尝试使用以下代码在正面和负面之间交替:

if(i%2 == 0)
    sum += -1 / ( 2 * i - 1); 
else
    sum += 1 / (2 * i - 1);

The series alternates between positive and negative numbers because of the numerator,

由于分子,该系列在正数和负数之间交替,

-1 ^ (i + 1).

-1 ^ (i + 1).

When the exponent is even, the numerator is positive. When the exponent is odd, the numerator is negative. Which means there no need to alternate between positive and negative numbers in your code since the formula inherently does that. Also, one must calculate the summation in the parenthesis 1st and then multiply by 4 at the end.

当指数为偶数时,分子为正。当指数为奇数时,分子为负。这意味着无需在代码中在正数和负数之间交替,因为公式本身就是这样做的。此外,必须计算括号 1 中的总和,然后在最后乘以 4。

Formula in code:To write the formula in code you should be aware that you will need Math.pow(base, exponent) method to a number to a power. For example, 2 ^ 3 is Math.pow(2, 3). With that method in mind the formula would like this:

代码中的公式在代码中编写公式,您应该知道您需要 Math.pow(base, exponent) 方法对数字进行幂运算。例如,2 ^ 3 是 Math.pow(2, 3)。考虑到该方法,公式将如下所示:

PI = 4 * (1 - 1/3 + 1/5 + ... + Math.pow(-1, i + 1) / (2 * i - 1));

Calculating PI:You can use a for loop to calculate PI by using a for loop like so:

计算 PI:您可以使用 for 循环通过使用 for 循环来计算 PI,如下所示:

for (int i = 10000; i > 0; i--) {
      PI += Math.pow(-1, i + 1) / (2 * i - 1); // Calculate series in parenthesis
      if (i == 1) { // When at last number in series, multiply by 4
        PI *= 4;    
        System.out.println(PI); // Print result
      }  
}

I have chosen to have my for loop start from 10000 and end when i = 1. The basic reason is that in Java, due to rounding of floating point numbers you'll obtain more accurate results if you add smaller numbers 1st and work your way to larger numbers. So, I am calculating the series from right to left instead of left to right. Then I allow the program to calculate the values in the parenthesis and only at the last number in the series does it multiply by 4 and print the result.

我选择让我的 for 循环从 10000 开始并在 i = 1 时结束。基本原因是在 Java 中,由于浮点数的四舍五入,如果您第一次添加较小的数字并按照自己的方式工作,您将获得更准确的结果到更大的数字。所以,我是从右到左而不是从左到右计算系列。然后我允许程序计算括号中的值,并且仅在系列中的最后一个数字上乘以 4 并打印结果。

Note you can replace 10000 with user input like so:

请注意,您可以使用用户输入替换 10000,如下所示:

java.util.Scanner input = new java.util.Scanner(System.in); //You can import instead
System.out.println("Enter number of loops: ");
int loops = input.nextInt();

for (int i = loops; i > 0; i--) {
...

回答by William Hanson

//Here is formula for how I would do PI approximations using Babylonian method.

//这是我如何使用巴比伦方法进行 PI 近似的公式。

int count = 10;
int m = 1;
int n = 0;
double pi = 0.0;
final double SQRT_12 = Math.sqrt(12);
while (count > n)
{
    pi += SQRT_12 * (Math.pow(-1, n)/(m * Math.pow(3, n)));
    System.out.println(pi);
    m += 2;
    n++;
}

回答by Sven Gurke

    double Pi = 0.0;
    long start = System.currentTimeMillis();
    for (double i = 1; i < 100000000; i++) {
        Pi += (i % 2 == 0) ? -1 / (2 * i - 1) : 1 / (2 * i - 1);
    }
    long stop = System.currentTimeMillis();
    System.out.println(Pi * 4);
    System.out.println(Math.PI);
    System.out.println(stop-start);
    // output:
    // 3.141592663589326
    // 3.141592653589793
    // 2426