Skip to content

Commit b5c6600

Browse files
Trashtalk217jiegillet
authored andcommitted
Lisp Monte Carlo (#514)
* First working version of monte carlo integration in lisp * Forgot to add docstring * Added error output. * Updated the output
1 parent fa1a094 commit b5c6600

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
;;;; Monte carlo integration to approximate pi
2+
3+
(defun in-circle-p (x y)
4+
"Checks if a point is in a unit circle"
5+
(< (+ (* x x) (* y y)) 1))
6+
7+
(defun monte-carlo (samples)
8+
"Returns an approximation of pi"
9+
(loop repeat samples
10+
with count = 0
11+
do
12+
(when (in-circle-p (random 1.0) (random 1.0))
13+
(incf count))
14+
finally (return (* (/ count samples) 4.0))))
15+
16+
(defvar pi-estimate (monte-carlo 5000000))
17+
(format t "Estimate: ~D ~%" pi-estimate)
18+
(format t "Error: ~D%" (* (/ (abs (- pi-estimate pi)) pi) 100))

contents/monte_carlo_integration/monte_carlo_integration.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@ each point is tested to see whether it's in the circle or not:
8181
[import:2-4, lang:"lisp"](code/racket/monte_carlo.rkt)
8282
{% sample lang="scala" %}
8383
[import:3-3, lang:"scala"](code/scala/monte_carlo.scala)
84+
{% sample lang="lisp" %}
85+
[import:3-5, lang:"lisp"](code/scala/monte-carlo.lisp)
8486
{% sample lang="asm-x64" %}
8587
[import:21-32, lang:"asm-x64"](code/asm-x64/monte_carlo.s)
8688
{% endmethod %}
@@ -163,6 +165,8 @@ Feel free to submit your version via pull request, and thanks for reading!
163165
[import, lang:"lisp"](code/racket/monte_carlo.rkt)
164166
{% sample lang="scala" %}
165167
[import, lang:"scala"](code/scala/monte_carlo.scala)
168+
{% sample lang="lisp" %}
169+
[import, lang:"lisp"](code/scala/monte-carlo.lisp)
166170
{% sample lang="asm-x64" %}
167171
[import, lang:"asm-x64"](code/asm-x64/monte_carlo.s)
168172
{% endmethod %}

0 commit comments

Comments
 (0)