exercise-5.scm (1969B)
1 (define-library (sicp solutions chapter-3 exercise-5) 2 (import (scheme base)) 3 (import (srfi :64 4 5 (begin 6 7 '( 8 A qed calculation: 9 a = number of heads 10 b = number of tails 11 n = number of heads and tails 12 13 a+b=n 14 15 C_i = +(1/(2^i)) if coin toss is heads else -(1/(2^i)) 16 17 (a - b) / 2^n = (sum i=1 to n C_i) 18 19 After n times, we get: 20 21 (a - b) / 2^n 22 ) 23 24 (define (random-plus-or-minus) 25 (- (* 2 26 (random 2)) 27 1)) 28 29 (define (random-unit-fraction deepness) 30 (define (iter current-deepness total) 31 (cond 32 ((<= current-deepness 0) 33 total) 34 (else 35 (iter (- current-deepness 1) 36 (+ total 37 (* (random-plus-or-minus) 38 (/ 1 39 (expt 2 40 current-deepness)))))))) 41 (iter deepness 0)) 42 43 (define (random-squared-confining-a-unit-circle deepness) 44 (cons (random-unit-fraction deepness) 45 (random-unit-fraction deepness))) 46 47 (define (in-unit-circle? x y) 48 (>= 1 (sqrt (+ (* x x) 49 (* y y))))) 50 51 (let ([random random:uniform]) 52 (define (random-in-range low high) 53 (let ([range (- high low)]) 54 (+ low (random range))))) 55 56 (define (monte-carlo trials experiment) 57 (define (iter trials-remaining trials-passed) 58 (cond ((= trials-remaining 0) 59 (/ trials-passed trials)) 60 ((experiment) 61 (iter (- trials-remaining 1) 62 (+ trials-passed 1))) 63 (else 64 (iter (- trials-remaining 1) 65 trials-passed)))) 66 (iter trials 0)) 67 68 8 * inside / total = tau 69 70 (= (/ area-of-circle 71 area-of-square) 72 (/ (* (/ tau 2)) 73 2)) 74 75 (define (estimate-integral p x1 x2 y1 y2 number-of-trials) 76 (monte-carlo number-of-trials ))))