From 7f183ba87d17fd3a02dbdb8ec318496e505b3ea8 Mon Sep 17 00:00:00 2001 From: earthfail Date: Sun, 1 Jul 2018 13:37:11 +0300 Subject: [PATCH 1/2] Add Monte Carlo in Clojure --- .../monte_carlo/code/clojure/monte_carlo.clj | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 chapters/monte_carlo/code/clojure/monte_carlo.clj diff --git a/chapters/monte_carlo/code/clojure/monte_carlo.clj b/chapters/monte_carlo/code/clojure/monte_carlo.clj new file mode 100644 index 000000000..f66baef67 --- /dev/null +++ b/chapters/monte_carlo/code/clojure/monte_carlo.clj @@ -0,0 +1,32 @@ +(ns monte-carlo.core) + +(defn in-circle? [pv r] + "take a vector representing point and radius return true if the + point is inside the circle" + (< (->> + pv + (map #(* % %)) + (reduce +)) + (* r r))) +(defn rand-point [r] + "return a random point from (0,0) inclusive to (r,r) exclusive" + (repeatedly 2 #(rand r))) +(defn monte-carlo [n r] + "take the number of random points and radius return an estimate to +pi" + (*' 4 (/ n) + (loop [i n count 0] + (if (zero? i) + count + (recur (dec i) + (if (in-circle? (rand-point r) r) + (inc count) + count)))))) +(defn -main [] + (let [constant-pi Math/PI + computed-pi (monte-carlo 10000000 2) ;; this may take some time on lower end machines + difference (Math/abs (- constant-pi computed-pi)) + error (* 100 (/ difference constant-pi))] + (println "world's PI: " constant-pi + ",our PI: " (double computed-pi) + ",error: " error))) From 3f3460397470624e6208614d34254c915c890455 Mon Sep 17 00:00:00 2001 From: earthfail Date: Sun, 1 Jul 2018 13:44:10 +0300 Subject: [PATCH 2/2] add clojure to monte_carlo.md --- chapters/monte_carlo/monte_carlo.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/chapters/monte_carlo/monte_carlo.md b/chapters/monte_carlo/monte_carlo.md index f021901cb..f882b78e3 100644 --- a/chapters/monte_carlo/monte_carlo.md +++ b/chapters/monte_carlo/monte_carlo.md @@ -39,6 +39,8 @@ each point is tested to see whether it's in the circle or not: {% method %} {% sample lang="jl" %} [import:2-7, lang:"julia"](code/julia/monte_carlo.jl) +{% sample lang="clj" %} +[import:3-10, lang:"clojure"](code/clojure/monte_carlo.clj) {% sample lang="c" %} [import:7-9, lang:"c_cpp"](code/c/monte_carlo.c) {% sample lang="js" %} @@ -85,6 +87,9 @@ Feel free to submit your version via pull request, and thanks for reading! {% sample lang="jl" %} ### Julia [import, lang:"julia"](code/julia/monte_carlo.jl) +{% sample lang="clj" %} +### Clojure +[import, lang:"clojure"](code/clojure/monte_carlo.clj) {% sample lang="c" %} ### C [import, lang:"c_cpp"](code/c/monte_carlo.c)