Calculating Pi Java Program

2019-02-19 02:18发布

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.

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

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 first 10,000 elements of the series and then display the result.

In addition to displaying the final result (your final 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.

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


    }
}

标签: java oop
4条回答
等我变得足够好
2楼-- · 2019-02-19 02:50

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

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

System.out.println(pi);

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

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 if statement

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);
}
查看更多
趁早两清
3楼-- · 2019-02-19 02:54

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

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++;
}
查看更多
【Aperson】
4楼-- · 2019-02-19 02:59

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.

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

查看更多
萌系小妹纸
5楼-- · 2019-02-19 03:03

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

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.

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:

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:

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.

Note you can replace 10000 with user input like so:

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--) {
...
查看更多
登录 后发表回答