Skip to content

Commit 0f5367f

Browse files
earthfailjiegillet
authored andcommitted
add monte carlo in clojure (#192)
* Add Monte Carlo in Clojure
1 parent 8367b34 commit 0f5367f

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
(ns monte-carlo.core)
2+
3+
(defn in-circle? [pv r]
4+
"take a vector representing point and radius return true if the
5+
point is inside the circle"
6+
(< (->>
7+
pv
8+
(map #(* % %))
9+
(reduce +))
10+
(* r r)))
11+
(defn rand-point [r]
12+
"return a random point from (0,0) inclusive to (r,r) exclusive"
13+
(repeatedly 2 #(rand r)))
14+
(defn monte-carlo [n r]
15+
"take the number of random points and radius return an estimate to
16+
pi"
17+
(*' 4 (/ n)
18+
(loop [i n count 0]
19+
(if (zero? i)
20+
count
21+
(recur (dec i)
22+
(if (in-circle? (rand-point r) r)
23+
(inc count)
24+
count))))))
25+
(defn -main []
26+
(let [constant-pi Math/PI
27+
computed-pi (monte-carlo 10000000 2) ;; this may take some time on lower end machines
28+
difference (Math/abs (- constant-pi computed-pi))
29+
error (* 100 (/ difference constant-pi))]
30+
(println "world's PI: " constant-pi
31+
",our PI: " (double computed-pi)
32+
",error: " error)))

chapters/monte_carlo/monte_carlo.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ each point is tested to see whether it's in the circle or not:
3939
{% method %}
4040
{% sample lang="jl" %}
4141
[import:2-7, lang:"julia"](code/julia/monte_carlo.jl)
42+
{% sample lang="clj" %}
43+
[import:3-10, lang:"clojure"](code/clojure/monte_carlo.clj)
4244
{% sample lang="c" %}
4345
[import:7-9, lang:"c_cpp"](code/c/monte_carlo.c)
4446
{% sample lang="js" %}
@@ -85,6 +87,9 @@ Feel free to submit your version via pull request, and thanks for reading!
8587
{% sample lang="jl" %}
8688
### Julia
8789
[import, lang:"julia"](code/julia/monte_carlo.jl)
90+
{% sample lang="clj" %}
91+
### Clojure
92+
[import, lang:"clojure"](code/clojure/monte_carlo.clj)
8893
{% sample lang="c" %}
8994
### C
9095
[import, lang:"c_cpp"](code/c/monte_carlo.c)

0 commit comments

Comments
 (0)