forked from algorithm-archivists/algorithm-archive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MonteCarlo.java
34 lines (27 loc) · 966 Bytes
/
MonteCarlo.java
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
//submitted by DominikRafacz
import java.util.Random;
public class MonteCarlo {
public static void main(String[] args) {
double piEstimation = monteCarlo(1000);
System.out.println("Estimated pi value: " + piEstimation);
System.out.printf("Percent error: " + 100 * (Math.PI - piEstimation) / Math.PI);
}
//function to check whether point (x,y) is in unit circle
private static boolean inCircle(double x, double y) {
return x * x + y * y < 1;
}
//function to calculate estimation of pi
public static double monteCarlo(int samples) {
int piCount = 0;
Random random = new Random();
for (int i = 0; i < samples; i++) {
double x = random.nextDouble();
double y = random.nextDouble();
if (inCircle(x, y)) {
piCount++;
}
}
double estimation = 4.0 * piCount / samples;
return estimation;
}
}