From bb72ed35137c9d756e8df9c502b4538b4414c629 Mon Sep 17 00:00:00 2001 From: Ramakrishnan Muthukrishnan <vu3rdd@gmail.com> Date: Thu, 6 Jan 2011 20:44:20 +0530 Subject: [PATCH] works fine in guile. Not that well in racket for 100000 iterations. --- src/sicp/ex3_5.rkt | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/sicp/ex3_5.rkt diff --git a/src/sicp/ex3_5.rkt b/src/sicp/ex3_5.rkt new file mode 100644 index 0000000..c93f777 --- /dev/null +++ b/src/sicp/ex3_5.rkt @@ -0,0 +1,35 @@ +#lang racket + +(define (monte-carlo trials experiment) + (define (iter trials-remaining trials-passed) + (cond + ((= trials-remaining 0) (/ trials-passed trials)) + ((experiment) (iter (- trials-remaining 1) (+ trials-passed 1))) + (else (iter (- trials-remaining 1) trials-passed)))) + (iter trials 0)) + +(define (square x) + (* x x)) + +(define (random-in-range low high) + (let ((range (- high low))) + (+ low (random range)))) + +(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 (estimate-integral P x1 x2 y1 y2 trials) + (define (in-region) + (let ((x (random-in-range x1 x2)) + (y (random-in-range y1 y2))) + (P x y))) + (define (rectangle-area x1 x2 y1 y2) + (* (- x2 x1) (- y2 y1))) + + (* (monte-carlo trials in-region) + (rectangle-area x1 x2 y1 y2))) + \ No newline at end of file -- 2.45.2