Skip to content

Commit

Permalink
Clean up Monte Carlo integration in Racket
Browse files Browse the repository at this point in the history
  • Loading branch information
berquist committed Oct 26, 2020
1 parent 18944ea commit 96ad3e4
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 19 deletions.
39 changes: 21 additions & 18 deletions contents/monte_carlo_integration/code/racket/monte_carlo.rkt
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
#lang racket
(define (in_circle x y)
(< (+ (sqr x) (sqr y)) 1)
)
#lang racket/base

(define (monte_carlo_pi n)
(* (/ (local ((define (monte_carlo* n count)
(require racket/local)
(require racket/math)

(define (in-circle x y)
"Checks if a point is in a unit circle"
(< (+ (sqr x) (sqr y)) 1))

(define (monte-carlo-pi n)
"Returns an approximation of pi"
(* (/ (local ((define (monte-carlo-pi* n count)
(if (= n 0)
count
(monte_carlo_pi* (sub1 n)
(if (in_circle (random) (random))
(add1 count)
count
)
)
)
)) (monte_carlo_pi* n 0)
) n) 4)
)

(monte-carlo-pi* (sub1 n)
(if (in-circle (random) (random))
(add1 count)
count)))))
(monte-carlo-pi* n 0)) n) 4))

(display (monte_carlo_pi 1000))
(define nsamples 5000000)
(define pi-estimate (monte-carlo-pi nsamples))
(displayln (string-append "Estimate (rational): " (number->string pi-estimate)))
(displayln (string-append "Estimate (float): " (number->string (real->single-flonum pi-estimate))))
(displayln (string-append "Error:" (number->string (* (/ (abs (- pi-estimate pi)) pi) 100))))
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ each point is tested to see whether it's in the circle or not:
{% sample lang="lua" %}
[import:2-4, lang="lua"](code/lua/monte_carlo.lua)
{% sample lang="racket" %}
[import:2-4, lang:"lisp"](code/racket/monte_carlo.rkt)
[import:6-8, lang:"lisp"](code/racket/monte_carlo.rkt)
{% sample lang="scala" %}
[import:3-3, lang:"scala"](code/scala/monte_carlo.scala)
{% sample lang="lisp" %}
Expand Down

0 comments on commit 96ad3e4

Please sign in to comment.