From 0a2764ad80d806747d61c4f298870aee0c6e61df Mon Sep 17 00:00:00 2001 From: CD Sigma Date: Tue, 3 Jul 2018 01:25:23 -0700 Subject: [PATCH] Small Change to Java implementation of Monte Carlo 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 --- chapters/monte_carlo/code/java/MonteCarlo.java | 11 +++++------ chapters/monte_carlo/monte_carlo.md | 2 +- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/chapters/monte_carlo/code/java/MonteCarlo.java b/chapters/monte_carlo/code/java/MonteCarlo.java index 1c368932c..39a1b2e10 100644 --- a/chapters/monte_carlo/code/java/MonteCarlo.java +++ b/chapters/monte_carlo/code/java/MonteCarlo.java @@ -4,7 +4,9 @@ public class MonteCarlo { public static void main(String[] args) { - monteCarlo(10_000_000); + 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 @@ -13,7 +15,7 @@ private static boolean inCircle(double x, double y) { } //function to calculate estimation of pi - public static void monteCarlo(int samples) { + public static double monteCarlo(int samples) { int piCount = 0; Random random = new Random(); @@ -27,9 +29,6 @@ public static void monteCarlo(int samples) { } double estimation = 4.0 * piCount / samples; - - System.out.println("Estimated pi value: " + estimation); - System.out.printf("Percent error: %.4f%%", - 100 * (Math.PI - estimation) / Math.PI); + return estimation; } } diff --git a/chapters/monte_carlo/monte_carlo.md b/chapters/monte_carlo/monte_carlo.md index 0d2621564..11c53e43c 100644 --- a/chapters/monte_carlo/monte_carlo.md +++ b/chapters/monte_carlo/monte_carlo.md @@ -54,7 +54,7 @@ each point is tested to see whether it's in the circle or not: {% sample lang="go" %} [import:12-14, lang:"golang"](code/go/monteCarlo.go) {% sample lang="java" %} -[import:11-13, lang:"java"](code/java/MonteCarlo.java) +[import:13-15, lang:"java"](code/java/MonteCarlo.java) {% sample lang="swift" %} [import:21-25, lang:"swift"](code/swift/monte_carlo.swift) {% endmethod %}