---
title: "Lab: multiple integrals in code"
heading: Grids, random points and coordinate changes
eyebrow: A9 · Lesson 20 · Lab: multiple integrals
xp: 60
---

::: hook
Lessons 14 to 19 evaluated integrals over regions by slicing and by changing coordinates. Most real regions and integrands don't have antiderivatives, and engineers integrate them numerically. In this lab you'll integrate over a non-rectangular region on a grid, estimate a volume by throwing random points, check the Gaussian-beam power formula in polar coordinates, find the centroid of a semicircular plate, and confirm the spherical Jacobian numerically.
:::

::: play
- Monte Carlo integration estimates an area or volume as the fraction of random points that land inside, times the box's size.
- The curve shows how its typical error shrinks with the number of points $N$: as $1/\sqrt N$.
- A grid rule's error in two dimensions shrinks much faster for smooth integrands, but in ten dimensions Monte Carlo wins, because its rate doesn't depend on the dimension.
:::

```sim plot
view: graph
x: N = 100..100000
y: error = 0.0001..0.5 log
slider: p = 0.1..0.9 step 0.05 = 0.52
plot: sqrt(p*(1 - p)/N)/p | label: relative error of a hit fraction p | samples: 400
readout: points for 1% relative error = ceil((1 - p)/(p*0.0001)) | digits: 6
```

::: predict
## A Monte Carlo estimate uses 10 000 points and has about 1% error. How many points would give 0.1%?

- [ ] 100 000
- [x] 1 000 000
- [ ] 20 000
- [ ] 10 000 000

::: reveal
A million. The error falls as $1/\sqrt N$, so ten times better needs a hundred times more points. That slow convergence is Monte Carlo's weakness in low dimensions, where a grid is far better, and its strength in high dimensions, where a grid would need impossibly many points.
:::
:::

::: nameit
## Grid rules in two dimensions

The midpoint rule samples the integrand at the center of each small cell and adds $f\,\Delta x\,\Delta y$. A region that isn't a rectangle can be handled by multiplying by an indicator that is 1 inside and 0 outside, though the jagged edge limits the accuracy to about the cell size.

## Monte Carlo

Draw $N$ uniform random points in a box of volume $V_\text{box}$. The fraction $p$ inside a region estimates its volume as $pV_\text{box}$, with a relative error of about $\sqrt{\frac{1 - p}{pN}}$. To integrate $f$, average $f$ at the points and multiply by $V_\text{box}$.

## Polar and spherical integrals in code

Changing coordinates puts the Jacobian into the integrand: $r$ in polar, $r^2\sin\varphi$ in spherical. A numerical integral in those coordinates uses a rectangular grid in $(r, \theta)$ or $(r, \varphi, \theta)$, weighted by the Jacobian.
:::

::: example
## Estimate the volume of the unit sphere by Monte Carlo with 200 000 points.

::: solution
1. **Sample the cube.** Draw points uniformly in the cube $[-1, 1]^3$ of volume 8, and count those with $x^2 + y^2 + z^2 \le 1$.
2. **Expected fraction.**
   $$\frac{4\pi/3}{8} = 0.524$$
3. **One run.** It gives a fraction of 0.5217, so the estimate is
   $$8 \times 0.5217 = 4.173$$
   against the true 4.189: 0.4% low.
4. **Compare with the expected error.**
   $$\sqrt{\frac{0.476}{0.524 \times 200\,000}} = 0.2\%$$
   The run is within twice that.

**Answer:** one run estimates the volume at 4.173, 0.4% below the true 4.189.
:::
:::

::: example
## Find the centroid of a semicircular plate of radius $R$.

::: solution
1. **Set up in polar coordinates.** The half disk is $0 \le r \le R$, $0 \le \theta \le \pi$, with
   $$\bar y = \frac{1}{A}\iint y\,dA, \quad A = \frac{\pi R^2}{2}$$
2. **Integrate $y$.**
   $$\iint r\sin\theta \cdot r\,dr\,d\theta = \frac{R^3}{3} \cdot 2$$
3. **Divide by the area.**
   $$\begin{aligned} \bar y &= \frac{2R^3/3}{\pi R^2/2} \\ &= \frac{4R}{3\pi} \\ &= 0.424R \end{aligned}$$
4. **Interpret.** Its balance point is a little under halfway up, because the plate is wider near the base.

**Answer:** the centroid sits on the axis of symmetry, $\frac{4R}{3\pi} = 0.424R$ above the straight edge.
:::
:::

::: check
given: p = 0.2 | 0.8 | 0.9; e = 1 | 0.1
answer: (1 - p)/(p*(e/100)^2)
tolerance: 1%

## A Monte Carlo region catches a fraction {p} of the points. About how many points give a relative error of {e}%?

::: right
Right. $N = \frac{1 - p}{p\,\varepsilon^2}$ = {answer}.
:::

::: misses
- [1/(e/100)^2] Small regions need more points: include $\frac{1 - p}{p}$.
- [any] Not yet. Solve $\sqrt{\frac{1 - p}{pN}} = \varepsilon$.
:::
:::

::: check
given: R = 1 | 3 | 10
answer: 4*R/(3*pi)
unit: cm
tolerance: 0.5%

## How far above its flat edge is the centroid of a semicircular plate of radius {R} cm?

::: right
Right. $\frac{4R}{3\pi}$ = {answer}.
:::

::: misses
- [R/2] It's a little less than halfway: the plate is wider near the base.
- [any] Not yet. $\bar y = \frac{1}{A}\iint y\,dA$ in polar coordinates.
:::
:::

::: check
kind: python

## Integrate $f = xy$ over the triangle $0 \le y \le x \le 1$ with the midpoint rule on an $n \times n$ grid over the unit square ($n$ = 400), using an indicator for the triangle. Set `I` and `exact` ($= \frac18$).

```python starter
import numpy as np

I = exact = 0.0
print(I, exact)
```

```python solution
import numpy as np

n = 400
h = 1 / n
c = (np.arange(n) + 0.5) * h
X, Y = np.meshgrid(c, c, indexing="ij")
I = np.sum(X * Y * (Y <= X)) * h * h
exact = 1 / 8
print(I, exact)
```

```python tests
assert exact == 0.125, "exact should be 1/8."
assert abs(I - 0.125) < 1e-3, f"The grid estimate should be within 1e-3 of 0.125; got {I}."
```

::: right
Right. The jagged diagonal edge costs some accuracy, but 400 × 400 cells get within a part in a thousand.
:::
:::

::: check
kind: python

## Estimate the unit sphere's volume by Monte Carlo: 200 000 points in $[-1, 1]^3$ from `np.random.default_rng(1)`. Set `vol`.

```python starter
import numpy as np

vol = 0.0
print(vol)
```

```python solution
import numpy as np

rng = np.random.default_rng(1)
p = rng.uniform(-1, 1, (200000, 3))
vol = 8 * np.mean((p**2).sum(axis=1) <= 1)
print(vol)
```

```python tests
import math
assert abs(vol - 4 * math.pi / 3) < 0.03, f"The volume is 4.189; Monte Carlo with 200 000 points should be within 0.03; got {vol}."
```

::: right
Right. A few tenths of a percent, as $1/\sqrt N$ predicts.
:::
:::

::: check
kind: python

## A Gaussian beam has $I = I_0e^{-2r^2/w^2}$ with $I_0$ = 2 W/cm² and $w$ = 1 mm. Integrate numerically in polar coordinates ($r$ from 0 to 5 mm, 2000 steps, trapezoid) and set `P` in watts and `formula` to $\frac{\pi w^2I_0}{2}$.

```python starter
import numpy as np

P = formula = 0.0
print(P, formula)
```

```python solution
import numpy as np

I0 = 2e4
w = 1e-3
r = np.linspace(0, 5e-3, 2001)
f = I0 * np.exp(-2 * r**2 / w**2) * r * 2 * np.pi
P = np.sum((f[1:] + f[:-1]) / 2 * np.diff(r))
formula = np.pi * w**2 * I0 / 2
print(P, formula)
```

```python tests
import math
assert abs(formula - math.pi * 1e-6 * 2e4 / 2) < 1e-12, "formula should be pi w^2 I0 / 2 in watts (I0 = 2e4 W/m^2)."
assert abs(P - formula) < 1e-5, f"The numerical power should match {formula:.6f} W; got {P}."
```

::: right
Right. 31.4 mW: the polar Jacobian $r$ turns the Gaussian into an integral you can do by hand, and the computer agrees.
:::
:::

::: check
kind: python

## Find the centroid height $\bar y$ of a semicircular plate of radius 1 numerically: integrate $y$ and 1 over $0 \le r \le 1$, $0 \le \theta \le \pi$ with the midpoint rule on a 300 × 300 polar grid (Jacobian $r$), and set `ybar`.

```python starter
import numpy as np

ybar = 0.5
print(ybar)
```

```python solution
import numpy as np

n = 300
r = (np.arange(n) + 0.5) / n
t = (np.arange(n) + 0.5) * np.pi / n
R, T = np.meshgrid(r, t, indexing="ij")
dA = R * (1 / n) * (np.pi / n)
ybar = np.sum(R * np.sin(T) * dA) / np.sum(dA)
print(ybar)
```

```python tests
import math
assert abs(ybar - 4 / (3 * math.pi)) < 1e-4, f"The centroid is 4/(3 pi) = 0.4244; got {ybar}."
```

::: right
Right. A polar grid fits the round edge exactly, so there's no jagged boundary and the error is tiny.
:::
:::

::: check
kind: python

## Check the spherical Jacobian numerically: write the map $(r, \varphi, \theta) \to (x, y, z)$, compute its 3 × 3 Jacobian matrix by central differences at $(2, 0.7, 1.1)$, and set `det` to its determinant and `formula` to $r^2\sin\varphi$.

```python starter
import numpy as np

det = formula = 0.0
print(det, formula)
```

```python solution
import numpy as np

def to_xyz(q):
    r, ph, th = q
    return np.array([r * np.sin(ph) * np.cos(th), r * np.sin(ph) * np.sin(th), r * np.cos(ph)])

q = np.array([2.0, 0.7, 1.1])
J = np.zeros((3, 3))
for k in range(3):
    e = np.zeros(3)
    e[k] = 1e-6
    J[:, k] = (to_xyz(q + e) - to_xyz(q - e)) / 2e-6
det = abs(np.linalg.det(J))
formula = q[0]**2 * np.sin(q[1])
print(det, formula)
```

```python tests
import math
assert abs(formula - 4 * math.sin(0.7)) < 1e-12, "formula should be r^2 sin(phi) = 4 sin(0.7)."
assert abs(det - formula) < 1e-6, f"The numerical Jacobian determinant should equal r^2 sin(phi) = {formula:.6f}; got {det}."
```

::: right
Right. The volume element $r^2\sin\varphi\,dr\,d\varphi\,d\theta$ is exactly the Jacobian, which the computer confirms.
:::
:::

::: explain
## Why does Monte Carlo integration beat a grid in high dimensions, even though it converges so slowly?

::: model
A grid rule with $n$ points per side in $d$ dimensions needs $n^d$ points, and its error for a smooth integrand shrinks like a power of $1/n$. In two dimensions that's cheap, but in ten dimensions even $n = 10$ means $10^{10}$ points. Monte Carlo's error is $\frac{\sigma}{\sqrt N}$ whatever the dimension, because it's a statistical average, and averages don't care how many coordinates each sample has. So beyond a handful of dimensions, a million random points give a usable answer where a grid can't even be built. Circuit yield analysis, with dozens of independently varying components, is a high-dimensional integral of exactly this kind.
:::
:::

::: practice

::: check
given: p = 0.05..0.95; e = 0.1..5
answer: (1 - p)/(p*(e/100)^2)
tolerance: 1%

## Points needed for {e}% relative error at hit fraction {p}?

::: misses
- [any] $\frac{1 - p}{p\varepsilon^2}$.
:::
:::

::: check
given: R = 0.1..100
answer: 4*R/(3*pi)
tolerance: 0.5%

## Centroid height of a semicircle of radius {R}?

::: misses
- [any] $\frac{4R}{3\pi}$.
:::
:::
:::
