Skip to content

Instantly share code, notes, and snippets.

@yao2030
Created December 25, 2012 08:19
Show Gist options
  • Save yao2030/4372241 to your computer and use it in GitHub Desktop.
Save yao2030/4372241 to your computer and use it in GitHub Desktop.
(define (random-in-range low high)
(let ((range (- high low)))
(+ low (random range))))
(define (experiment x1 x2 y1 y2)
(let ((a (random-in-range x1 x2))
(b (random-in-range y1 y2))
(c (/ (+ x1 x2) 2.0))
(d (/ (+ y1 y2) 2.0))
(r (/ (- x1 x2) 2.0)))
(<= (+ (square (- a c))
(square (- b d)))
(square r))))
(define (monte-carlo p x1 x2 y1 y2 trials)
(define (iter trials-remaining trials-passed)
(cond ((= trials-remaining 0)
(/ (* 1.0 trials-passed) trials))
((p x1 x2 y1 y2)
(iter (- trials-remaining 1) (+ 1 trials-passed)))
(else
(iter (- trials-remaining 1) trials-passed))))
(iter trials 0))
;; 3.5
(define (pi)
(* 4.0 (monte-carlo experiment 0 1.0 0 1.0 10000)))
;; 3.6
(define rand
(let ((x random-init))
(lambda (m)
(cond ((eq? m 'generate) (set! x (rand-update x)) x)
((eq? m 'reset) (lambda (y) (set! x y)))
(else (error "Sorry"))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment