Exercise 3.5:
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 P
(
x
,
y
) that is true for points (
x
,
y
) in the
region and false for points not in the region. For example, the region
contained within a circle of radius 3 centered at (5, 7) is described by the
predicate that tests whether (
x
−
5
)
2
+
(
y
−
7
)
2
≤
3
2. To estimate
the area of the region described by such a predicate, begin by choosing a
rectangle that contains the region. For example, a rectangle with diagonally
opposite corners at (2, 4) and (8, 10) contains the circle above. The desired
integral is the area of that portion of the rectangle that lies in the region.
We can estimate the integral by picking, at random, points (
x
,
y
) that
lie in the rectangle, and testing P
(
x
,
y
) for each point to
determine whether the point lies in the region. If we try this with many
points, then the fraction of points that fall in the region should give an
estimate of the proportion of the rectangle that lies in the region. Hence,
multiplying this fraction by the area of the entire rectangle should produce an
estimate of the integral.
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 π.
Use your estimate-integral to produce an estimate of π by
measuring the area of a unit circle.
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 nonnegative number less than its
input.
(define (random-in-range low high)
(let ((range (- high low)))
(+ low (random range))))
练习 3.5:蒙特卡罗积分 (Monte Carlo integration) 是一种借助蒙特卡罗模拟 (Monte Carlo simulation) 来估算定积分的方法。考虑计算由谓词 P(x, y) 描述的空间区域的面积——P(x, y) 对区域内的点 (x, y) 为真,对区域外的点为假。例如,以 (5, 7) 为圆心、半径为 3 的圆内的区域,由检验 (x − 5)² + (y − 7)² ≤ 3² 的谓词来描述。要估算这样一个谓词所描述的区域面积,首先选取一个包含该区域的矩形。例如,对角顶点分别为 (2, 4) 和 (8, 10) 的矩形包含了上述圆。所需积分就是该矩形中落在区域内的部分的面积。我们可以通过随机选取矩形内的点 (x, y) 并对每个点检验 P(x, y) 来估算积分,以判断该点是否在区域内。若对许多点进行这样的试验,落在区域内的点所占的比例就应当给出矩形中属于该区域部分的比例估算。因此,将这一比例乘以整个矩形的面积,就应当得到积分的估算值。
将蒙特卡罗积分实现为过程 estimate-integral,它以谓词 P、矩形的上下界 x1、x2、y1、y2 以及试验次数为参数,产生估算值。你的过程应使用前面用于估算 π 的同一个 monte-carlo 过程。用你的 estimate-integral 通过测量单位圆面积来产生 π 的一个估算值。
你会发现有一个过程很有用,它能在给定范围内随机返回一个数。下面的 random-in-range 过程借助 1.2.6 节中使用的 random 过程(返回一个小于其输入的非负数)来实现这一功能:
(define (random-in-range low high)
(let ((range (- high low)))
(+ low (random range))))
(define (random-in-range low high)
(let ((range (- high low)))
(+ low (random range))))