diff --git a/chapters/monte_carlo/code/d/monte_carlo.d b/chapters/monte_carlo/code/d/monte_carlo.d new file mode 100644 index 000000000..324282daa --- /dev/null +++ b/chapters/monte_carlo/code/d/monte_carlo.d @@ -0,0 +1,29 @@ +///Returns true if a point (x, y) is in the circle with radius r +bool inCircle(real x, real y) +{ + return x ^^ 2 + y ^^ 2 < 1.0; +} + +///Calculate pi using monte carlo +real monteCarloPI(ulong n) +{ + import std.algorithm : count; + import std.random : uniform01; + import std.range : generate, take; + import std.typecons : tuple; + + auto piCount = generate(() => tuple!("x", "y")(uniform01, uniform01)) + .take(n) + .count!(a => inCircle(a.x, a.y)); + return piCount * 4.0 / n; +} + +void main() +{ + import std.math : abs, PI; + import std.stdio : writeln; + + auto p = monteCarloPI(100_000); + writeln("Estimated pi: ", p); + writeln("Percent error: ", abs(p - PI) * 100 / PI); +} diff --git a/chapters/monte_carlo/monte_carlo.md b/chapters/monte_carlo/monte_carlo.md index 8b283a3bd..846dcc6f6 100644 --- a/chapters/monte_carlo/monte_carlo.md +++ b/chapters/monte_carlo/monte_carlo.md @@ -45,6 +45,8 @@ each point is tested to see whether it's in the circle or not: [import:7-7, lang:"haskell"](code/haskell/monteCarlo.hs) {% sample lang="rs" %} [import:7-9, lang:"rust"](code/rust/monte_carlo.rs) +{% sample lang="d" %} +[import:2-5, lang:"d"](code/rust/monte_carlo.d) {% endmethod %} 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! {%sample lang="rs" %} ### Rust [import, lang:"rust"](code/rust/monte_carlo.rs) +### D +{%sample lang="d" %} +[import, lang:"d"](code/d/monte_carlo.d) {% endmethod %}