Skip to content

Commit 0b5a6fd

Browse files
DominikRafaczzsparal
authored andcommitted
Added MonteCarlo in Java (#188)
* Added monte carlo method in Java * fixed number of lines in md file * Set fixed radius to 1 * Corrected code style
1 parent 53185b2 commit 0b5a6fd

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

CONTRIBUTORS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,4 @@ Chinmaya Mahesh
1313
Unlambder
1414
Kjetil Johannessen
1515
CDsigma
16+
DominikRafacz
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
//submitted by DominikRafacz
2+
import java.util.Random;
3+
4+
public class MonteCarlo {
5+
6+
public static void main(String[] args) {
7+
monteCarlo(10_000_000);
8+
}
9+
10+
//function to check whether point (x,y) is in unit circle
11+
private static boolean inCircle(double x, double y) {
12+
return x * x + y * y < 1;
13+
}
14+
15+
//function to calculate estimation of pi
16+
public static void monteCarlo(int samples) {
17+
int piCount = 0;
18+
19+
Random random = new Random();
20+
21+
for (int i = 0; i < samples; i++) {
22+
double x = random.nextDouble();
23+
double y = random.nextDouble();
24+
if (inCircle(x, y)) {
25+
piCount++;
26+
}
27+
}
28+
29+
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);
34+
}
35+
}

chapters/monte_carlo/monte_carlo.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ each point is tested to see whether it's in the circle or not:
5353
[import:2-5, lang:"d"](code/d/monte_carlo.d)
5454
{% sample lang="go" %}
5555
[import:12-14, lang:"golang"](code/go/monteCarlo.go)
56+
{% sample lang="java" %}
57+
[import:11-13, lang:"java"](code/java/MonteCarlo.java)
5658
{% endmethod %}
5759

5860
If it's in the circle, we increase an internal count by one, and in the end,
@@ -108,6 +110,9 @@ Feel free to submit your version via pull request, and thanks for reading!
108110
{%sample lang="go" %}
109111
### Go
110112
[import, lang:"golang"](code/go/monteCarlo.go)
113+
{% sample lang="java" %}
114+
### Java
115+
[import, lang:"java"](code/java/MonteCarlo.java)
111116
{% endmethod %}
112117

113118

0 commit comments

Comments
 (0)