Search code examples
javapi

Pi Number Calculation gives 3.22


I'm trying to calculate pi number using this formula: pi/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 ...

   public class Calculator
{
  double process=1;
  double piValue=0;
  int approximation;
  double value;
  public Calculator( int precision)
  {
    approximation = precision;
  }

  public void calculate()
  {
    while(process<=approximation)
    {
      value = 1/(process+2);
      if(process%2==0)
      {
        value = value;
      }
      else
      {
        value = value * (-1);
      }
      piValue = piValue + value;
      process++;
    }
    System.out.println((1+piValue)*4.0);

  }
}

I see nothing wrong here but i keep getting very meaningless outputs. Here are some examples:

23. step: 3.1490100018286853 This is OK.
1501. step: 3.22874239242146
100,000 step: 3.2274312772602247

So its limit while "step number" goes to infinity is around 3.22 . How can i fix this problem?

I have just started studying Java, please keep in mind that.

Thanks in advance.


Solution

  • When calculating value at the top of the while loop, your use of process is incorrect; you'll wind up calculating -1/3 + 1/4 - 1/5 + ....

    Instead of

    value = 1/(process+2);
    

    try

    value = 1/(2*process + 1);
    

    Now this will advance the denominator by odd numbers starting with 3, which is ok because you're adding 1 at the very end.

    With this change and 1,501 loops, I get 3.1409268747021875 -- pretty close for this method of calculating pi. (100,000 loops prints 3.141602653489781.)