---
title: "Lab: improper integrals in code"
heading: Integrating to infinity on a computer that can't go there
eyebrow: A6 · Lesson 9 · Lab: improper integrals in code
xp: 60
---

::: hook
A computer can't integrate out to infinity, but it can integrate far enough that the rest doesn't matter, and know when it has. That's how a simulator computes the total energy of a decaying pulse, and how a numerical Laplace transform works. In this lab you'll write an integrator that keeps extending its range until the new pieces are negligible, a numerical Laplace transform checked against the table, and an energy calculation for a ringing pulse checked against its exact formula.
:::

::: play
- The curve is $\frac{1}{1 + x^2}$. The shaded region runs from 0 to $L$, and the readout compares its area with the full area to infinity, $\pi/2$.
- Double $L$ again and again. The missing area, $\frac\pi2 - \tan^{-1}L$, is about $1/L$: halving with each doubling.
- An integrand that falls like $e^{-x}$ would leave a tail of $e^{-L}$, far faster.
:::

```sim plot
view: graph
x: x = 0..40
y: y = 0..1.05
slider: L = 1..40 = 4
plot: 1/(1 + x^2) | samples: 400 | label: 1/(1 + x²)
marker: x = L | label: L
readout: area to L = atan(L) | digits: 5
readout: missing tail = pi/2 - atan(L) | digits: 4
```

::: predict
## An integrator adds pieces $[a, a + 1], [a + 1, a + 3], [a + 3, a + 7], \ldots$, each twice as long as the last, and stops when a piece adds less than $10^{-10}$. For $\int_0^\infty e^{-x}dx$, about how far out does it get?

- [ ] About 10
- [x] About 30
- [ ] About $10^{10}$
- [ ] It never stops

::: reveal
About 30. A piece starting at $x$ adds about $e^{-x}$ (times the piece's length, which grows only by doubling), so pieces fall below $10^{-10}$ once $x$ passes about $\ln 10^{10} = 23$, at the end of the piece that starts at 15 and ends at 31. For $\frac{1}{1 + x^2}$ the pieces shrink only as $1/x$, so it would need to reach about $10^{10}$: slowly decaying tails are the hard case.
:::
:::

::: nameit
## Extending the range

To approximate $\int_a^\infty f$:
1. integrate a first piece, say $[a, a + 1]$, with Simpson's rule;
2. keep adding pieces of doubling length;
3. stop when a piece contributes less than the tolerance.

Doubling means a slowly decaying tail can still be reached in a reasonable number of steps. The stopping test assumes the pieces keep shrinking, which holds for integrands that decay steadily.

## A numerical Laplace transform

$F(s) = \int_0^\infty e^{-st}f(t)\,dt$. The factor $e^{-st}$ makes the integrand negligible beyond $T = \frac{\ln(1/\text{tol})}{s}$, so integrating on $[0, T]$ is enough, as long as $f$ itself doesn't grow fast.

## Checking against exact answers

A numerical integrator is trusted after it reproduces known results: $\int_0^\infty\frac{dx}{1 + x^2} = \frac\pi2$, $\mathcal L\{e^{at}\} = \frac{1}{s - a}$, $\mathcal L\{\sin\omega t\} = \frac{\omega}{s^2 + \omega^2}$. For a ringing pulse $v = V_0e^{-t/\tau}\sin\omega t$ across $R$, the energy is

$$\int_0^\infty\frac{v^2}{R}dt = \frac{V_0^2}{2R}\left(\frac1a - \frac{a}{a^2 + 4\omega^2}\right), \qquad a = \frac2\tau$$

from $\sin^2 = \tfrac12(1 - \cos 2\omega t)$ and the transforms of 1 and $\cos$.
:::

::: example
## How far must you integrate $e^{-st}\sin 3t$ for its Laplace transform at $s = 4$ to be accurate to $10^{-12}$?

::: solution
1. **Bound the tail.** The integrand is at most $e^{-4t}$, whose tail beyond $T$ is
   $$\int_T^\infty e^{-4t}\,dt = \frac{e^{-4T}}{4}$$
2. **Solve for $T$.** Set $e^{-4T} = 10^{-12}$:
   $$\begin{aligned} T &= \frac{12\ln 10}{4} \\ &= 6.9 \end{aligned}$$
3. **Check with Simpson's rule.** Simpson's rule on $[0, 6.9]$ with 4000 slices gives 0.119 999 999 99, against the exact $\frac{3}{25} = 0.12$.

**Answer:** integrating out to $T = 6.9$ is enough.
:::
:::

::: example
## A 10 V ringing pulse, $v = 10e^{-t/1\,\text{ms}}\sin(2\pi \cdot 1000\,t)$, appears across 100 Ω. How much energy does it deliver?

::: solution
1. **Use the damped-sine integral.** With $a = 2/\tau = 2000$ per second and $\omega = 2\pi \times 1000$:
   $$\begin{aligned} E &= \frac{100}{200}\left(\frac{1}{2000} - \frac{2000}{2000^2 + 4\omega^2}\right) \\ &= 0.5(0.0005 - 0.0000123) \\ &= 0.244\ \text{mJ} \end{aligned}$$
2. **Check numerically.** Integrating numerically for 30 time constants agrees to ten digits.

**Answer:** the pulse delivers 0.244 mJ.
:::
:::

::: check
given: tol = 0.000001 | 0.000000000001; s = 1 | 4 | 10
answer: ln(1/tol)/s
tolerance: 0.5%

## A numerical Laplace transform at $s$ = {s} stops where $e^{-st}$ falls below {tol}. How far does it integrate?

::: right
Right. $T = \frac{\ln(1/\text{tol})}{s}$ = {answer}.
:::

::: misses
- [log(1/tol)/s] Use the natural log: $e^{-sT}$ = tol.
- [any] Not yet. Solve $e^{-sT}$ = tol.
:::
:::

::: check
given: L = 10 | 100 | 1000
answer: pi/2 - atan(L)
tolerance: 0.5%

## How much of $\int_0^\infty\frac{dx}{1 + x^2}$ lies beyond $x$ = {L}?

::: right
Right. $\frac\pi2 - \tan^{-1}L$ = {answer}, about $1/L$.
:::

::: misses
- [1/L^2] The integrand falls as $1/x^2$, but its tail integral falls as $1/L$.
- [any] Not yet. Subtract the area up to {L} from $\pi/2$.
:::
:::

::: check
kind: python

## Write `to_inf(f, a, tol=1e-10)`: integrate `f` from `a` to infinity by adding Simpson's-rule pieces (200 slices each) of length 1, 2, 4, ..., stopping when a piece adds less than `tol` in size. Use the `simpson` in the starter.

```python starter
import math

def simpson(f, a, b, n=200):
    h = (b - a) / n
    s = f(a) + f(b)
    for k in range(1, n):
        s += (4 if k % 2 else 2) * f(a + k * h)
    return s * h / 3

def to_inf(f, a, tol=1e-10):
    return simpson(f, a, a + 1)

print(to_inf(lambda x: 1 / (1 + x * x), 0))
```

```python solution
import math

def simpson(f, a, b, n=200):
    h = (b - a) / n
    s = f(a) + f(b)
    for k in range(1, n):
        s += (4 if k % 2 else 2) * f(a + k * h)
    return s * h / 3

def to_inf(f, a, tol=1e-10):
    total, lo, L = 0.0, a, 1.0
    while True:
        piece = simpson(f, lo, lo + L)
        total += piece
        lo += L
        L *= 2
        if abs(piece) < tol:
            return total

print(to_inf(lambda x: 1 / (1 + x * x), 0))
```

```python tests
import math
assert abs(to_inf(lambda x: 1 / (1 + x * x), 0) - math.pi / 2) < 1e-8, "The integral of 1/(1 + x^2) from 0 is pi/2."
assert abs(to_inf(lambda x: math.exp(-x), 0) - 1) < 1e-8, "The integral of e^-x from 0 is 1."
assert abs(to_inf(lambda x: 1 / x**2, 1) - 1) < 1e-8, "The integral of 1/x^2 from 1 is 1."
```

::: right
Right. Doubling the pieces lets even a $1/x^2$ integrand reach its limit in a few dozen steps.
:::
:::

::: check
kind: python

## Write `laplace(f, s, tol=1e-12)`, the numerical Laplace transform: integrate $e^{-st}f(t)$ from 0 to $T = \ln(1/\text{tol})/s$ with Simpson's rule and 4000 slices. Check it against the table.

```python starter
import math

def simpson(f, a, b, n=200):
    h = (b - a) / n
    s = f(a) + f(b)
    for k in range(1, n):
        s += (4 if k % 2 else 2) * f(a + k * h)
    return s * h / 3

def laplace(f, s, tol=1e-12):
    return 0

print(laplace(lambda t: math.sin(3 * t), 4))
```

```python solution
import math

def simpson(f, a, b, n=200):
    h = (b - a) / n
    s = f(a) + f(b)
    for k in range(1, n):
        s += (4 if k % 2 else 2) * f(a + k * h)
    return s * h / 3

def laplace(f, s, tol=1e-12):
    T = math.log(1 / tol) / s
    return simpson(lambda t: math.exp(-s * t) * f(t), 0, T, 4000)

print(laplace(lambda t: math.sin(3 * t), 4))
```

```python tests
import math
assert abs(laplace(lambda t: math.sin(3 * t), 4) - 3 / 25) < 1e-8, "L{sin 3t} at s = 4 is 3/25."
assert abs(laplace(lambda t: math.exp(-2 * t), 3) - 0.2) < 1e-8, "L{e^-2t} at s = 3 is 1/5."
assert abs(laplace(lambda t: t, 2) - 0.25) < 1e-8, "L{t} at s = 2 is 1/4."
assert abs(laplace(lambda t: math.cos(5 * t), 1) - 1 / 26) < 1e-8, "L{cos 5t} at s = 1 is 1/26."
```

::: right
Right. Every row of the table checks out, which is the evidence that both the code and the table are right.
:::
:::

::: check
kind: python
given: tau = 0.5 | 1 | 2; f = 500 | 1000

## A pulse $v = 10e^{-t/\tau}\sin(2\pi ft)$ volts, with $\tau$ = {tau} ms and $f$ = {f} Hz, appears across 100 Ω. Set `E_num` to its energy by Simpson's rule over 30 time constants with 20 000 slices, and `E_exact` from the formula in the reading.

```python starter
import math

E_num = E_exact = 0
print(E_num, E_exact)
```

```python solution
import math

def simpson(f, a, b, n=200):
    h = (b - a) / n
    s = f(a) + f(b)
    for k in range(1, n):
        s += (4 if k % 2 else 2) * f(a + k * h)
    return s * h / 3

V0, R, T = 10, 100, tau * 1e-3
w = 2 * math.pi * f
E_num = simpson(lambda t: (V0 * math.exp(-t / T) * math.sin(w * t))**2 / R, 0, 30 * T, 20000)
a = 2 / T
E_exact = V0**2 / (2 * R) * (1 / a - a / (a * a + 4 * w * w))
print(E_num, E_exact)
```

```python tests
import math
T, w = tau * 1e-3, 2 * math.pi * f
a = 2 / T
want = 100 / 200 * (1 / a - a / (a * a + 4 * w * w))
assert abs(E_exact - want) < 1e-15, "E_exact should come from the formula."
assert abs(E_num - want) / want < 1e-8, f"The numerical energy should match {want:.6e} J; got {E_num:.6e}."
```

::: right
Right. The formula and the numbers agree to many digits: each is a check on the other.
:::
:::

::: check
kind: python
given: N = 5 | 10 | 20 | 50 | 100 | 1000

## By the integral test, the tail of $\sum\frac{1}{n^2}$ after $N$ terms lies between $\frac{1}{N + 1}$ and $\frac1N$. Set `S` to the sum of the first `N` = {N} terms, `lo` and `hi` to `S` plus those two bounds, and `true` to $\pi^2/6$. Check that `true` lies between `lo` and `hi`.

```python starter
import math

S = lo = hi = true = 0
print(lo, true, hi)
```

```python solution
import math

S = sum(1 / n**2 for n in range(1, N + 1))
lo = S + 1 / (N + 1)
hi = S + 1 / N
true = math.pi**2 / 6
print(lo, true, hi)
```

```python tests
import math
assert lo < math.pi**2 / 6 < hi, f"pi^2/6 should lie between {lo} and {hi}."
assert abs(hi - lo - (1 / N - 1 / (N + 1))) < 1e-15, "The bracket's width is 1/N - 1/(N + 1)."
assert abs(true - math.pi**2 / 6) < 1e-15, "true should be pi^2/6."
```

::: right
Right. With 100 terms the bracket is about $10^{-4}$ wide; the sum alone is off by $10^{-2}$. Adding the integral's estimate of the tail is far cheaper than adding terms.
:::
:::

::: check
kind: python

## A slowly decaying tail can be moved to a finite range. With $x = 1/u$, $\int_1^\infty\frac{dx}{1 + x^2} = \int_0^1\frac{du}{1 + u^2}$. Set `I` to the right side by Simpson's rule with 200 slices, and `exact` to $\pi/4$.

```python starter
import math

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

```python solution
import math

def simpson(f, a, b, n=200):
    h = (b - a) / n
    s = f(a) + f(b)
    for k in range(1, n):
        s += (4 if k % 2 else 2) * f(a + k * h)
    return s * h / 3

I = simpson(lambda u: 1 / (1 + u * u), 0, 1)
exact = math.pi / 4
print(I, exact)
```

```python tests
import math
assert abs(I - math.pi / 4) < 1e-12, f"The substitution turns the tail into pi/4 on [0, 1]; got {I}."
```

::: right
Right. Two hundred slices on a finite interval beat dozens of doubling pieces reaching toward infinity.
:::
:::

::: explain
## Why is $\int_0^\infty\frac{dx}{1 + x^2}$ much harder to compute numerically than $\int_0^\infty e^{-x}dx$, even though both are finite?

::: model
Both integrands decay, but at very different rates. The tail of $e^{-x}$ beyond $L$ is $e^{-L}$, so stopping at $L$ = 30 already leaves less than $10^{-13}$. The tail of $\frac{1}{1 + x^2}$ is about $\frac1L$: to leave less than $10^{-10}$, the integration has to reach $x \approx 10^{10}$. Doubling the pieces makes that reachable in about 35 pieces, but each piece still costs work, and a stopping rule based on the size of the last piece can stop too early if the integrand flattens. In practice, slowly decaying tails are handled by a substitution such as $x = 1/u$, which turns the infinite range into a finite one, or by adding the tail's known asymptotic form.
:::
:::

::: practice

::: check
given: tol = 0.000000000001..0.001; s = 0.1..20
answer: ln(1/tol)/s
tolerance: 0.5%

## Laplace cutoff: tol {tol}, $s$ = {s}?

::: misses
- [any] $\ln(1/\text{tol})/s$.
:::
:::

::: check
given: L = 1..10000
answer: pi/2 - atan(L)
tolerance: 0.5%

## Tail of $\int\frac{dx}{1 + x^2}$ beyond {L}?

::: misses
- [any] $\frac\pi2 - \tan^{-1}L$.
:::
:::
:::
