-
-
Notifications
You must be signed in to change notification settings - Fork 357
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Clean up Monte Carlo integration in Racket (#781)
* Clean up Monte Carlo integration in Racket * Add blank lines in Monte Carlo integration in Clojure * Change Racket lang include from lisp to racket
- Loading branch information
Showing
3 changed files
with
27 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
39 changes: 21 additions & 18 deletions
39
contents/monte_carlo_integration/code/racket/monte_carlo.rkt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters