Skip to content

Commit daef028

Browse files
committed
added class PiNilakantha.java
which calculates Pi using Nilakanthas infinite series
1 parent cebd052 commit daef028

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

Maths/PiNilakantha.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package Maths;
2+
3+
public class PiNilakantha {
4+
5+
// Calculates Pi using Nilakantha's infinite series
6+
7+
public static void main(String[] args) {
8+
assert calculatePi(0) == 3.0;
9+
assert calculatePi(10) > 3.0;
10+
assert calculatePi(100) < 4.0;
11+
12+
System.out.println(calculatePi(500));
13+
}
14+
15+
16+
/**
17+
*
18+
* @param iterations number of times the infinite series gets repeated
19+
* Pi get more accurate the higher the value of iterations is
20+
* Values from 0 up to 500 are allowed since double precision is not sufficient
21+
* for more than about 500 repetitions of this algorithm
22+
* @return the pi value of the calculation with a precision of x iteration
23+
*/
24+
public static double calculatePi(int iterations) {
25+
if (iterations < 0 || iterations > 500) {
26+
throw new IllegalArgumentException("Please input Integer Number between 0 and 500");
27+
}
28+
29+
double pi = 3;
30+
int divCounter = 2;
31+
32+
for (int i = 0; i < iterations; i++) {
33+
34+
if (i % 2 == 0)
35+
pi = pi + 4.0 / (divCounter * (divCounter + 1) * (divCounter + 2));
36+
else
37+
pi = pi - 4.0 / (divCounter * (divCounter + 1) * (divCounter + 2));
38+
39+
divCounter += 2;
40+
}
41+
return pi;
42+
}
43+
}

0 commit comments

Comments
 (0)