20 hours ago
my attempt to do the exercises in sicp.
Thursday, January 6, 2011
sicp exercise 3.82
;; Exercise 3.82. Redo exercise 3.5 on Monte Carlo integration in terms of streams. The stream version of estimate-integral will not have an argument telling how many trials to perform. Instead, it will produce a stream of estimates based on successively more trials.
;; get-random-stream is a procedure which generates a stream of random pairs of (x,y) which lie within x1 y1 x2 y2
(define (estimate-integral integral x1 x2 y1 y2)
(define input (get-random-stream x1 x2 y1 y2))
(define area (abs (* (- x1 x2) (- y1 y2))))
(define (iter passed total in-stream)
(let ((x (car (stream-car in-stream)))
(y (cdr (stream-car in-stream))))
(if (integral x y)
(cons-stream (* area (/ (+ passed 1) (+ 1 total)))
(iter (+ 1 passed) (+ 1 total) (stream-cdr in-stream)))
(cons-stream (* area (/ passed (+ 1 total)))
(iter passed (+ 1 total) (stream-cdr in-stream))))))
(iter 0 0 input))
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment