1

I tried to make a program (in Java) that calculates pi with the Chudnovsky algorithm but it has the output NaN (Not a Number). Please help me find mistakes in my code, or improve my code. (I don't have a lot of Java programming knowledge)

You can find Chudnovsky's algorithm here:

https://en.wikipedia.org/wiki/Chudnovsky_algorithm

here is my code:

package main;

public class Class1 {

    public static void main(String[] args)
    {
        double nr1=0,nr2=0,nr3=0,pi=0;
        int fo1=1, fo2=1, fo3=1;

        for(int i=0; i<=20; i++){

            for(int fl1=1; fl1<=(6*i); fl1++){fo1 = fo1 * fl1;}
            for(int fl2=1; fl2<=(3*i); fl2++){fo2 = fo2 * fl2;}
            for(int fl3=1; fl3<=(i); fl3++){fo3 = fo3 * fl3;}

            nr1 = ( (Math.pow(-1, i)) * (fo1) * ((545140134*i) + 13591409) );
            nr2 = ( (fo2) * (Math.pow(fo3, i)) * ( Math.pow(Math.pow(640320, 3), (i+(1/2)) )) );
            nr3 = 12 * (nr1/nr2);

        }

        pi = 1/nr3;
        System.out.println((Math.PI));
        System.out.println(pi);
    }
}
Kedar Mhaswade
  • 4,535
  • 2
  • 25
  • 34
  • `i+(1/2)` probably doesn't do what you think. It doesn't evaluate to `i+0.5`, it evaluates to `i`. – Andy Turner Mar 17 '16 at 12:04
  • Also, I doubt that `int` is an appropriate type for `fo1`, `fo2`, `fo3`. You appear to be calculating factorials like 120! which is way bigger than `Integer.MAX_VALUE`. – Andy Turner Mar 17 '16 at 12:08

1 Answers1

3

There are many issues here.

  • As Andy mentioned, 1/2 is not 0.5.
  • You are using integers to compute things like 120! which is completely out of bounds for any primitive type.
  • f01,f02,f03 should be initialized inside each loop, otherwise they grow even bigger

It is not trivial to fix it. You can take a look at Error calculating pi using the Chudnovsky algorithm - Java and http://www.craig-wood.com/nick/articles/pi-chudnovsky/ for some hints, but don't expect built-in primitive types to work with that algorithm.

Community
  • 1
  • 1
Artur Biesiadowski
  • 3,595
  • 2
  • 13
  • 18