Skip to content

Lisp Monte Carlo #514

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Oct 17, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions contents/monte_carlo_integration/code/lisp/monte-carlo.lisp
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
;;;; Monte carlo integration to approximate pi

(defun in-circle-p (x y)
"Checks if a point is in a unit circle"
(< (+ (* x x) (* y y)) 1))

(defun monte-carlo (samples)
"Returns an approximation of pi"
(loop repeat samples
with count = 0
do
(when (in-circle-p (random 1.0) (random 1.0))
(incf count))
finally (return (* (/ count samples) 4.0))))

(defvar pi-estimate (monte-carlo 5000000))
(format t "Estimate: ~D ~%" pi-estimate)
(format t "Error: ~D%" (* (/ (abs (- pi-estimate pi)) pi) 100))
4 changes: 4 additions & 0 deletions contents/monte_carlo_integration/monte_carlo_integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ each point is tested to see whether it's in the circle or not:
[import:2-4, lang:"lisp"](code/racket/monte_carlo.rkt)
{% sample lang="scala" %}
[import:3-3, lang:"scala"](code/scala/monte_carlo.scala)
{% sample lang="lisp" %}
[import:3-5, lang:"lisp"](code/scala/monte-carlo.lisp)
{% sample lang="asm-x64" %}
[import:21-32, lang:"asm-x64"](code/asm-x64/monte_carlo.s)
{% endmethod %}
Expand Down Expand Up @@ -163,6 +165,8 @@ Feel free to submit your version via pull request, and thanks for reading!
[import, lang:"lisp"](code/racket/monte_carlo.rkt)
{% sample lang="scala" %}
[import, lang:"scala"](code/scala/monte_carlo.scala)
{% sample lang="lisp" %}
[import, lang:"lisp"](code/scala/monte-carlo.lisp)
{% sample lang="asm-x64" %}
[import, lang:"asm-x64"](code/asm-x64/monte_carlo.s)
{% endmethod %}
Expand Down