Search code examples
javaalgorithmbigdecimal

Approximating Pi in java using Gauss-Legendre algorithm


Just started picking up java and tried to write a simple piece of code to display an approximation of Pi based on the Gauss-Legendre algorithm; the result I get in the command line from the code below is -33.343229... which seems very odd to me. I am aware that my code is not complete as I do not have a restriction on the number of digits after the decimal point, which I was going to try and get from using BigDecimal. I don't quite understand what I am supposed to do with it though after reading the documentation!

Does anyone have any idea if there are any current mistakes I can fix and also how to implement a restriction on the number of digits after the decimal point? Thank you!

class calculatePi {
public static void main(String[] args) {
    calculatePi x = new calculatePi();
    double y = x.approxPi(3);       //3 iterations
        System.out.print(y);
}
double approxPi(int i) {
    double a = 1;           //The initial conditions for the iteration
    double b = 1 / Math.sqrt(2);
    double t = 1/4;
    double p = 1;
    double a1 = 0;          //The internal n+1 terms for the iteration
    double b1 = 0;
    double t1 = 0;
    double p1 = 0;
    while (i > 0) {
        a1 = (a + b) / 2;
        b1 = Math.sqrt(a*b);
        t1 = t - p*(a - a1)*(a - a1);
        p1 = 2*p;
        a = a1;
        b = b1;
        t = t1;
        p = p1;
        i = i - 1;
    }
double applepie = ((a + b)*(a + b))/(4*t);
return applepie;
}

}


Solution

  • double t = 1/4; does an integer division for 1/4, which results in 0. Try 1/4.0.