Gauss Legendre algorithm in java

Hi, coders! Mathematics is a very important part in the life of coders. As you all know there are so many  Mathematics algorithms that we implement through code.
In this tutorial, We are going to learn Gauss Legendre algorithm in Java which is based on the computation of the digits of π(pi). This method is completely based on the modern algorithm for multiplication and square roots. This method works by continuously replacing two numbers with their geometric and arithmetic mean so as to approximate their arithmetic and geometric mean.

Gauss Legendre Algorithm

  • We are using some arrays (ar, br, tr, pr) of type double, elements of these arrays are used to calculate the desired result.
  • Set ar[0] = 1 , br[0] = 1/√2, tr[0] = 1/4, pr[0] = 1.
  • For different values of array elements, use formulae:

                ar[i] = (ar[i-1] + br[i-1])/2;

                br[i] = Math.sqrt(ar[i-1]*br[i-1]);

                tr[i] = tr[i-1] – pr[i-1]*(ar[i-1] – ar[i])*(ar[i-1] – ar[i]);

                pr[i] = 2*pr[i-1];

  • Then π(pi) is approximated as:

                 π(pi) = ((ar[av-1] + br[av-1])*(ar[av-1] + br[av-1]))/(4*tr[av-1]);

Note: Here (av) is used to know upto which digit accuracy is required and (i) is the iterating variable for arrays.

Implementation of Gauss Legendre Algorithm in Java

import java.util.*;
public class GaussLegendre {
static int av;
// driver function
  public static void main(String[] args) {
         Scanner sc = new Scanner(System.in)
         System.out.println("enter the approximation value");
         av = sc.nextInt();
         double y = approxPi();  /*function that calculates value of pie*/
         System.out.print("hence pi value is "+y);
  }
 private static double approxPi() {
    double[] ar = new double[av];
    double[] br = new double[av];
    double[] tr = new double[av];
    double[] pr = new double[av];   
   for(int i  = 1; i < av; i++) { 
      /* initializing first value of all arrays */
     ar[0] = 1;
     br[0] = 1/Math.sqrt(2);
     tr[0] = 1/4.0;
     pr[0] = 1;
     ar[i] = (ar[i-1] + br[i-1])/2;
         
     br[i] = Math.sqrt(ar[i-1]*br[i-1]);
          
     tr[i] = tr[i-1]-pr[i-1]*(ar[i-1]-ar[i])*(ar[i-1]-ar[i]);
       
     pr[i] = 2*pr[i-1];
}
            
  double pie = ((ar[av-1]+br[av-1])*(ar[av-1]+br[av-1]))/(4*tr[av-1]);
  return pie;
  }


}
//Code is provided by Anubhav Srivastava

 

Output:

enter the approximation value
3
hence pi value is 3.141592646213543

Hence, the Gauss Legendre algorithm is used to calculate the value of π(pi).
Hope you like the content.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *