Guass Legendre Algorithm

The Gauss-Legendre algorithm is an iterative method used for computing the numerical value of the mathematical constant pi (π) with high levels of precision. It was first developed by German mathematicians Carl Friedrich Gauss and Adrien-Marie Legendre in the late 18th and early 19th centuries. This algorithm converges quadratically, meaning that the number of correct decimal places approximately doubles with each iteration, making it an efficient method for calculating π to a large number of decimal places. It has been widely used in the field of numerical analysis, especially in the computation of mathematical constants and the evaluation of numerical integrals. The algorithm is based on the arithmetic-geometric mean (AGM) and a series of iterative formulas involving square roots and arithmetic operations. The initial values for the algorithm are determined, and then each iteration refines these values, bringing the approximation of π closer to its true value. At each step of the algorithm, several intermediate variables are computed, which are then used to update the main variables involved in the calculations. The iterations are repeated until the desired level of precision is achieved. Over the years, the Gauss-Legendre algorithm has been improved and optimized, leading to the discovery of millions of digits of π and contributing to the advancement of computational mathematics.
package Others;

import java.lang.Math;

/**
 * Guass Legendre Algorithm
 * ref https://en.wikipedia.org/wiki/Gauss–Legendre_algorithm
 *
 * @author AKS1996
 */
public class GuassLegendre {

    public static void main(String[] args) {
        for (int i = 1; i <= 3; ++i)
            System.out.println(pi(i));

    }

    static double pi(int l) {
        /*
         * l: No of loops to run
         */

        double a = 1, b = Math.pow(2, -0.5), t = 0.25, p = 1;
        for (int i = 0; i < l; ++i) {
            double temp[] = update(a, b, t, p);
            a = temp[0];
            b = temp[1];
            t = temp[2];
            p = temp[3];
        }

        return Math.pow(a + b, 2) / (4 * t);
    }

    static double[] update(double a, double b, double t, double p) {
        double values[] = new double[4];
        values[0] = (a + b) / 2;
        values[1] = Math.sqrt(a * b);
        values[2] = t - p * Math.pow(a - values[0], 2);
        values[3] = 2 * p;

        return values;
    }

}

LANGUAGE:

DARK MODE: