> Java Question -- Calculate PI by iteration?

Java Question -- Calculate PI by iteration?

Posted at: 2014-12-18 
You are doing too many calculations. A lot can be simplified. Try this for loop

double sum = 0;

int n = 1;

for (int i=1; i<=terms; ++i)

{

sum += (double) (n * (4.0 / (2 * i - 1)));

n = (n == -1)? 1: -1;

}

Also change your print statement:

System.out.print("i="+terms+" pi="+sum+"\tcontinue (y|n)?");

the 4*sum is not needed and is probably a source of your problems.

The big problem is that you don't reset sum to 0 when you repeat the loop. The second is that you are using integer division instead of floating point, which you can fix by changing either or both ones to 1.0 instead of 1. The following also fixes both problems:

A nice way to handle the +/- signs without division (% does integer division to get a remainder....slow!) in the loop is to start with this in front of your loop:

double one = 1.0;

sum = 0.0;

....then in the loop:

sum += one / (i+i+1);

one = -one;

By starting "one" at 4.0 instead of 1.0, you can even get the multiplication by 4 built into the loop with no computational cost.

Hi Kenny. In your "for" loop, you need to have a range from 1 to terms like this:

for(int i=1; i<=terms; i++){

And you need to add in a new line right after the "do{" statement:

sum = 0;

Good luck!

To whom it may concern,

I am writing a program to compute PI by iteration. Perhaps a common formula known as one of many to compute PI is the following:

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

I am trying to write code that shows the value of pi for various values of i. Starting with i=1 and showing the approximation when i=1, I then prompt the user. If the user wants to continue, I am to double the value of i and recompute the approximation of pi. In short, I am to display the approximation value of pi until the user chooses not to continue.

The problem I am having is this: I keep getting values that do not make sense. At first I was getting values that were way too small. Then I made some changes from some research I found on my own, and now the estimates are way too big. Can someone offer some guidance?

Here is my code:

// Create a Scanner object & define variables

Scanner kb = new Scanner (System.in);

int terms = 1; double sum = 0;

String entry=""; char choice='-';

//do-while user chooses to continue

do{

// PI calculation

for(int i=0; i
if(i%2 == 0) // if the term is positive

sum += -1 / ( 2 * i - 1); //for even terms we add negative numbers

else

sum += 1 / (2 * i - 1);

}//end for

//output format: i=1 pi=4.0 continue (y|n)? y

System.out.print("i="+terms+" pi="+4*sum+"\tcontinue (y|n)?");

entry = kb.nextLine();

choice = entry.charAt(0);

if(choice == 'y')

terms*=2;

}while(choice=='y');