SICP Exercise 3.5
Question
Monte Carlo integration is a method of estimating definite integrals by means
of Monte Carlo simulation. Consider computing the area of a region of space
described by a predicate
Implement Monte Carlo integration as a procedure estimate-integral that takes
as arguments a predicate P, upper and lower bounds x1, x2, y1, and y2
for the rectangle, and the number of trials to perform in order to produce the
estimate. Your procedure should use the same monte-carlo procedure that was
used above to estimate estimate-integral to produce an estimate
of
You will find it useful to have a procedure that returns a number chosen at
random from a given range. The following random-in-range procedure implements
this in terms of the random procedure used in 1.2.6, which returns a non-negative
number less than its input.
(define (random-in-range low high)
(let ((range (- high low)))
(+ low (random range))))
Answer
Here’s my solution:
(define (experiment x1 x2 y1 y2 radius)
(<= (+
(square (random-in-range x1 x2))
(square (random-in-range y1 y2)))
radius))
(define (estimate-integral x1 x2 y1 y2 trials)
(define rect_area (* (- x2 x1) (- y2 y1)))
(* rect_area (monte-carlo
trials
(λ () (experiment x1 x2 y1 y2 1.0)))))
Let’s run it 100,000 times:
(estimate-integral -1.0 1.0 -1.0 1.0 100000)
Result is quite close to trials:
3.14948