Graphics Reference
In-Depth Information
Listing 30.5: Estimating the integral of the real-valued function f on an
interval, version 2.
1
2
3
4
5
6
def integrate2(double
*
f (double), double a, double b):
// estimate the integral of f on [a, b]
x1 = uniform(a, b)
// random real number in [a, b]
x2 = uniform(a, b)
// second random real number in [a, b]
y = 0.5
*
((
*
f)(x1) + (
*
f)(x2));
// average the results
return y
*
(b-a)
// multiply by length of interval
It seems intuitively obvious that the expected value here is still the integral
of
f
on
[
a
,
b
]
. Let's verify that. In mathematical terms, we have two random vari-
ables,
X
1
and
X
2
, each with a uniform distribution on
[
a
,
b
]
. We then compute
Y
=
2
(
f
(
X
1
)+
f
(
X
2
))
. What is
E
[(
b
−
a
)
Y
]
? Using the linearity of expectation,
we see that
a
)
1
E
[(
b
−
a
)
Y
]=
E
[(
b
−
2
(
f
(
X
1
)+
f
(
X
2
))]
(30.52)
=
1
2
E
[(
b
−
a
)(
f
(
X
1
)+
f
(
X
2
))]
(30.53)
=
1
2
(
E
[(
b
−
a
)
f
(
X
1
)] +
E
[(
b
−
a
)
f
(
X
2
)])
(30.54)
=
1
2
(
2
E
[(
b
−
a
)
f
(
X
1
)])
(30.55)
The last equality follows because
X
1
and
X
2
have the same distribution. Thus it
follows that
E
[(
b
−
a
)
Y
]=
E
[(
b
−
a
)
f
(
X
1
)]
(30.56)
=
b
a
f
(
x
)
dx
.
(30.57)
What about the variance?
Var
[
Y
]=
Var
[
1
2
(
f
(
X
1
)+
f
(
X
2
))]
(30.58)
=
1
4
Var
[
f
(
X
1
)+
f
(
X
2
)]
(30.59)
=
1
4
(
Var
[
f
(
X
1
)] +
Var
[
f
(
X
2
)])
(30.60)
=
1
4
(
2
Var
[
f
(
X
1
)])
(30.61)
=
1
2
Var
[
f
(
X
1
)]
.
(30.62)
When we averaged two samples, the expectation remained the same, but the
variance w
en
t down by a factor of two. (The standard deviation went down by a
factor of
√
2). If we define
Y
n
by
n
Y
n
=
1
n
f
(
X
i
)
,
(30.63)
i
=
1