diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 410bdd576..807513539 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -13,3 +13,4 @@ Chinmaya Mahesh Unlambder Kjetil Johannessen CDsigma +DominikRafacz diff --git a/chapters/monte_carlo/code/java/MonteCarlo.java b/chapters/monte_carlo/code/java/MonteCarlo.java new file mode 100644 index 000000000..1c368932c --- /dev/null +++ b/chapters/monte_carlo/code/java/MonteCarlo.java @@ -0,0 +1,35 @@ +//submitted by DominikRafacz +import java.util.Random; + +public class MonteCarlo { + + public static void main(String[] args) { + monteCarlo(10_000_000); + } + + //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 void 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; + + System.out.println("Estimated pi value: " + estimation); + System.out.printf("Percent error: %.4f%%", + 100 * (Math.PI - estimation) / Math.PI); + } +} diff --git a/chapters/monte_carlo/monte_carlo.md b/chapters/monte_carlo/monte_carlo.md index c312370df..dbb350fa3 100644 --- a/chapters/monte_carlo/monte_carlo.md +++ b/chapters/monte_carlo/monte_carlo.md @@ -49,6 +49,8 @@ each point is tested to see whether it's in the circle or not: [import:2-5, lang:"d"](code/d/monte_carlo.d) {% sample lang="go" %} [import:12-14, lang:"golang"](code/go/monteCarlo.go) +{% sample lang="java" %} +[import:11-13, lang:"java"](code/java/MonteCarlo.java) {% endmethod %} If it's in the circle, we increase an internal count by one, and in the end, @@ -98,6 +100,9 @@ Feel free to submit your version via pull request, and thanks for reading! {%sample lang="go" %} ### Go [import, lang:"golang"](code/go/monteCarlo.go) +{% sample lang="java" %} +### Java +[import, lang:"java"](code/java/MonteCarlo.java) {% endmethod %}