Search code examples
javapi

Why do I get "NaN" as Outprint`?


I want to calculat Pi with Java. With S. Ramanujan formel.

Heres my code:

public class PiV5 {
public static void main(String[] args) {
int a = 4;
double pi = 0;
int b = 3;
int fakult = 3;

int x = 3; 
long y = 1;
    for (int i =1; i <= 50; i++) {
        int n = i*4; 
        long fakultaet = 1;
        long fakultae2 = 1; 
        int bh = i;
        for (int g=1; g<=n; g++) {fakultaet = fakultaet * g;}
        for (int l=1; l<=bh; l++) {fakultae2 = fakultae2 * l;}

        pi = ((fakultaet * (1103 + (26390*i)))/Math.pow(fakultae2, 4) * Math.pow(396, 4*i));

    };
        System.out.println("Pi nach ein paar Rechnungen: " + (Math.sqrt(8)/9801)*pi);

    }
}

Thanks for ur help, if you could help me


Solution

  • As Andreas mentioned in the comments this calculation results in a numeric overflow, because the values getting to large even for long data types.

    The maximum steps you can do with your algorithm right now is 5, because 20! = 2432902008176640000, 21! = -4249290049419214848 which is caused by the numeric overflow.

    But even then you have a little error in your code, because you forgot to sum up the values in the loop:

    pi += ((fakultaet * (1103 + (26390 * i))) / Math.pow(fakultae2, 4) * Math.pow(396, 4 * i));
    

    To get a better accuracy also use double values for the constant values:

    pi += ((fakultaet * (1103d + (26390d * i))) / Math.pow(fakultae2, 4) * Math.pow(396, 4 * i));
    

    Using that with 5 iterations will result in the following:

    Pi nach ein paar Rechnungen: 4.0513767058512194E63
    

    This is not quite a good result for PI.

    To improve it and get better accuracy you could use BigDecimal class.