From: Ramakrishnan Muthukrishnan Date: Sun, 7 Aug 2011 18:12:36 +0000 (+0530) Subject: solution to 3.82 X-Git-Url: https://git.rkrishnan.org/webform_css?a=commitdiff_plain;h=0ff16488171d1c541d946be772d86d67ac67f3a1;p=sicp.git solution to 3.82 --- diff --git a/src/sicp/ex3_82.rkt b/src/sicp/ex3_82.rkt new file mode 100644 index 0000000..a8351bf --- /dev/null +++ b/src/sicp/ex3_82.rkt @@ -0,0 +1,37 @@ +#lang racket + +(define (random-in-range low high) + (let ((range (- high low))) + (+ low (* (random) range)))) + +(define (point-stream x1 x2 y1 y2) + (cons-stream + (list (random-in-range x1 x2) + (random-in-range y1 y2)) + (point-stream x1 x2 y1 y2))) + +(define (P x y) + (define (inside-circle? radius centre-x centre-y) + (<= (+ (square (- x centre-x)) + (square (- y centre-y))) + (square radius))) + (inside-circle? 1.0 0 0)) + +(define (monte-carlo experiment-stream passed failed) + (define (next passed failed) + (cons-stream + (/ passed (+ passed failed)) + (monte-carlo + (stream-cdr experiment-stream) passed failed))) + (if (stream-car experiment-stream) + (next (+ passed 1) failed) + (next passed (+ failed 1)))) + +(define (estimate-integral P x1 x2 y1 y2) + (monte-carlo (stream-map (lambda (p) + (apply P p)) + (point-stream x1 x2 y1 y2)) + 0 + 0)) + +(* (stream-ref (estimate-integral P 1 -1 1 -1) 100000) 4.0) diff --git a/src/sicp/streams.rkt b/src/sicp/streams.rkt index e4252cd..b0540ae 100644 --- a/src/sicp/streams.rkt +++ b/src/sicp/streams.rkt @@ -1,5 +1,7 @@ #lang planet neil/sicp +(#%require (only racket random)) + (define (stream-car s) (car s)) (define (stream-cdr s) (force (cdr s)))