Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c497d13

Browse files
authored
Added class that calculated Pi (TheAlgorithms#2324)
* added class PiNilakantha.java which calculates Pi using Nilakanthas infinite series * added link to explanation partially fixes TheAlgorithms#2323
1 parent 0f75446 commit c497d13

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

‎Maths/PiNilakantha.java

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

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /