# Help computing Pi!

• October 28th, 2013, 12:21 PM
manooloo
Help computing Pi!
Hi. We have been asked to compute Pi with the formula:

PI = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) + ...
Allowing the user to determine the amount of computations to perform(5 shown in the above formula)

I'm completely stumped at this stage and cannot get the correct answer no matter what I try. Does anyone have any idea where a problem is in this code?

Code:

```import javax.swing.JOptionPane; import java.util.Scanner; public class pi { public static void main(String[] args)         {         String digitInput = JOptionPane.showInputDialog( "How many terms would you like to be used in the computation?");         Scanner termScan = new Scanner (digitInput);                 double terms = termScan.nextDouble();                                 double pistart = 3;                 double termCount = 0;                 double num1 = 2;                 double num2 = 3;                 double num3 = 4;                 double four = 4;                 while (termCount <= terms)                 {                                                                 double piloop = (four/(num1 * num2 * num3));                         double finalpi = pistart + piloop;                         num1 = num1 + 2;                         num2 = num2 + 2;                         num3 = num3 + 2;                                                 four = four * (-1);                         termCount ++;                                                 JOptionPane.showMessageDialog(null, + finalpi);                                         }                } }```
• October 30th, 2013, 06:50 AM
Norm
Re: Help computing Pi!
Try printing out the values of each term as they are computed to see if they are correctly computed.

Move the JOptionPane call outside of the loop
• October 30th, 2013, 05:12 PM
khaahk
Re: Help computing Pi!
Each time you loop you overwrite the double finalpi with the statement
double finalpi = pistart + piloop;
pistart needs to be used only the first time. Either move it out of the loop or check if it is the first time the loop executed and then use the pistart.