Skip to content

Commit cecf806

Browse files
author
AKS1996
committed
Guass Legendre Algorithm for approximation of pi
1 parent b71360c commit cecf806

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Others/GuassLengendre.java

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import java.lang.Math;
2+
/*
3+
* author: @AKS1996
4+
* Guass Legendre Algorithm
5+
* ref https://en.wikipedia.org/wiki/Gauss–Legendre_algorithm
6+
*
7+
*/
8+
9+
public class GuassLegendre {
10+
11+
public static void main(String[] args) {
12+
for(int i=1;i<=3;++i)
13+
System.out.println(pi(i));
14+
15+
}
16+
17+
static double pi(int l){
18+
/*
19+
* l: No of loops to run
20+
*/
21+
22+
double a = 1,b=Math.pow(2,-0.5),t=0.25,p=1;
23+
for(int i=0;i<l;++i){
24+
double temp[] = update(a,b,t,p);
25+
a = temp[0];
26+
b = temp[1];
27+
t = temp[2];
28+
p = temp[3];
29+
}
30+
31+
return Math.pow(a+b, 2)/(4*t);
32+
}
33+
34+
static double[] update(double a, double b, double t, double p){
35+
double values[] = new double[4];
36+
values[0] = (a+b)/2;
37+
values[1] = Math.sqrt(a*b);
38+
values[2] = t - p*Math.pow(a - values[0],2);
39+
values[3] = 2*p;
40+
41+
return values;
42+
}
43+
44+
}

0 commit comments

Comments
 (0)