-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathComputePI.java
More file actions
46 lines (40 loc) · 1.29 KB
/
ComputePI.java
File metadata and controls
46 lines (40 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Write a program called ComputePI to compute the value of π,
* using the following series expansion. You have to decide on the termination
* criterion used in the computation (such as the number of terms used
* or the magnitude of an additional term).
*
* PI = 4 * (1 -1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - 1/15 ...)
*/
package javaexercises.flowcontrol;
/**
*
* @author User
*/
public class ComputePI {
public static void main(String[] args) {
double precision = 0.0000001;
ComputePI aComputePI = new ComputePI();
double pi = aComputePI.getPI(precision);
System.out.printf("Difference between the values obtained and the Math.PI: %.10f \n", (double)(Math.PI - pi));
}
/**
* Compute PI value with precision.
*
* @param double precision
* @return double
*/
private double getPI(double precision) {
double sumOld;
double sumNew = 0.0;
long i = 0;
do {
sumOld = sumNew;
sumNew += ((i % 2 == 0) ? 1 : -1) * (double) 4/(2*i + 1);
++i;
} while( (double) Math.abs(sumNew - sumOld) >= precision);
System.out.printf("Calculated items %d, PI = %.10f", i, sumOld);
System.out.println();
return sumOld;
}
}