Skip to content

Commit 39bbbf6

Browse files
Wesley-Arringtonzsparal
authored andcommitted
Small Change to Java implementation of Monte Carlo (#210)
Changed the monteCarlo function to return a double so print statements are done in main() I think the code is a bit cleaner this way but it may just be a personal preference so I understand if this isn't merged
1 parent 2d8d2ef commit 39bbbf6

File tree

2 files changed

+6
-7
lines changed

2 files changed

+6
-7
lines changed

chapters/monte_carlo/code/java/MonteCarlo.java

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
public class MonteCarlo {
55

66
public static void main(String[] args) {
7-
monteCarlo(10_000_000);
7+
double piEstimation = monteCarlo(1000);
8+
System.out.println("Estimated pi value: " + piEstimation);
9+
System.out.printf("Percent error: " + 100 * (Math.PI - piEstimation) / Math.PI);
810
}
911

1012
//function to check whether point (x,y) is in unit circle
@@ -13,7 +15,7 @@ private static boolean inCircle(double x, double y) {
1315
}
1416

1517
//function to calculate estimation of pi
16-
public static void monteCarlo(int samples) {
18+
public static double monteCarlo(int samples) {
1719
int piCount = 0;
1820

1921
Random random = new Random();
@@ -27,9 +29,6 @@ public static void monteCarlo(int samples) {
2729
}
2830

2931
double estimation = 4.0 * piCount / samples;
30-
31-
System.out.println("Estimated pi value: " + estimation);
32-
System.out.printf("Percent error: %.4f%%",
33-
100 * (Math.PI - estimation) / Math.PI);
32+
return estimation;
3433
}
3534
}

chapters/monte_carlo/monte_carlo.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ each point is tested to see whether it's in the circle or not:
5454
{% sample lang="go" %}
5555
[import:12-14, lang:"golang"](code/go/monteCarlo.go)
5656
{% sample lang="java" %}
57-
[import:11-13, lang:"java"](code/java/MonteCarlo.java)
57+
[import:13-15, lang:"java"](code/java/MonteCarlo.java)
5858
{% sample lang="swift" %}
5959
[import:21-25, lang:"swift"](code/swift/monte_carlo.swift)
6060
{% endmethod %}

0 commit comments

Comments
 (0)