Skip to content

Commit 6fd1371

Browse files
SirSireeshzsparal
authored andcommitted
Add D implementation of monte carlo (#162)
* Add d implementation of monte carlo * cleanup d version of monte carlo
1 parent 320c980 commit 6fd1371

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
///Returns true if a point (x, y) is in the circle with radius r
2+
bool inCircle(real x, real y)
3+
{
4+
return x ^^ 2 + y ^^ 2 < 1.0;
5+
}
6+
7+
///Calculate pi using monte carlo
8+
real monteCarloPI(ulong n)
9+
{
10+
import std.algorithm : count;
11+
import std.random : uniform01;
12+
import std.range : generate, take;
13+
import std.typecons : tuple;
14+
15+
auto piCount = generate(() => tuple!("x", "y")(uniform01, uniform01))
16+
.take(n)
17+
.count!(a => inCircle(a.x, a.y));
18+
return piCount * 4.0 / n;
19+
}
20+
21+
void main()
22+
{
23+
import std.math : abs, PI;
24+
import std.stdio : writeln;
25+
26+
auto p = monteCarloPI(100_000);
27+
writeln("Estimated pi: ", p);
28+
writeln("Percent error: ", abs(p - PI) * 100 / PI);
29+
}

chapters/monte_carlo/monte_carlo.md

+5
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ each point is tested to see whether it's in the circle or not:
4545
[import:7-7, lang:"haskell"](code/haskell/monteCarlo.hs)
4646
{% sample lang="rs" %}
4747
[import:7-9, lang:"rust"](code/rust/monte_carlo.rs)
48+
{% sample lang="d" %}
49+
[import:2-5, lang:"d"](code/rust/monte_carlo.d)
4850
{% endmethod %}
4951

5052
If it's in the circle, we increase an internal count by one, and in the end,
@@ -88,6 +90,9 @@ Feel free to submit your version via pull request, and thanks for reading!
8890
{%sample lang="rs" %}
8991
### Rust
9092
[import, lang:"rust"](code/rust/monte_carlo.rs)
93+
### D
94+
{%sample lang="d" %}
95+
[import, lang:"d"](code/d/monte_carlo.d)
9196
{% endmethod %}
9297

9398

0 commit comments

Comments
 (0)