---
title: "Lab: limits, derivatives and integrals in code"
heading: Largest δ, mean value points, Taylor bounds, Riemann sums and improper tails
eyebrow: A14 · Lesson 22 · Lab: limits, derivatives and integrals in code
xp: 60
---

::: hook
Lessons 11 to 20 proved the theorems of one-variable calculus: continuity with ε and δ, the mean value theorem, Taylor's theorem with remainder, the Riemann integral and improper integrals. Each theorem promises a number exists or a bound holds. In this lab you'll compute those numbers. You'll find the largest δ by bisection, locate a mean value point, compare Taylor errors with their bounds, find how many strips squeeze the upper and lower sums together, and evaluate an improper integral by truncating it and adding an exact tail.
:::

::: play
- The curve is $x^2$ near the point a, and the band is $f(a) \pm \varepsilon$.
- The readout gives the largest δ such that every x within δ of a stays in the band: $\sqrt{a^2 + \varepsilon} - a$, set by the right side, where $x^2$ climbs faster.
- Move a further from 0: δ shrinks, about $\frac{\varepsilon}{2a}$. That's why $x^2$ is continuous everywhere but not uniformly continuous on all of ℝ.
:::

```sim plot
view: graph
x: x = 0..4
y: y = 0..12
slider: a = 0.5..3 step 0.1 = 2
slider: e = 0.1..2 step 0.1 = 1
plot: x^2 | label: x² | samples: 300
plot: a^2 + e | dashed | label: upper edge of the band
plot: a^2 - e | dashed | label: lower edge | color: ch3
readout: largest delta = sqrt(a^2 + e) - a | digits: 4
```

::: predict
## For $x^2$ at a = 2 with ε = 0.1, is the largest δ set by the left side or the right side of a?

- [ ] The left side
- [x] The right side
- [ ] Both equally
- [ ] Neither: δ is unlimited

::: reveal
The right side. $x^2$ rises faster to the right of 2 than it falls to the left, so it leaves the band first on the right, at $\sqrt{4.1} = 2.0248$. The left side would allow $2 - \sqrt{3.9} = 0.0252$; the right allows only 0.0248, and δ must work on both sides.
:::
:::

::: nameit
## Bisection on δ

For a continuous f, "every x in $(a - \delta, a + \delta)$ satisfies $\lvert f(x) - f(a)\rvert < \varepsilon$" is true for small δ and false past the largest one, so bisection finds it. Checking the condition on a fine grid is an approximation, good enough for smooth f.

## Locating a mean value point

For f differentiable on [a, b], solve $f'(c) = \frac{f(b) - f(a)}{b - a}$. When f′ is monotone, bisection finds the unique c.

## Bounds against actual errors

Taylor's theorem bounds the error by $\frac{M\lvert x - a\rvert^{n+1}}{(n + 1)!}$. Computing the actual error shows how much the bound overestimates. For a monotone function, $U - L = \frac{\lvert f(b) - f(a)\rvert(b - a)}{n}$ exactly.

## Truncating an improper integral

Split $\int_1^\infty = \int_1^B + \int_B^\infty$: compute the first numerically and the second exactly or by a bound. For $\frac{\ln x}{x^2}$ the tail is exactly $\frac{\ln B + 1}{B}$.
:::

::: example
## Find the mean value point c for $e^x$ on [0, 2] by bisection.

::: solution
1. **Slope of the chord.**
   $$\frac{e^2 - 1}{2} = 3.1945$$
   so c solves $e^c = 3.1945$.
2. **Bisect.** Since $e^c$ increases, bisect on [0, 2]: the bracket closes on
   $$c = 1.161439$$
3. **Check against the exact answer.** That's $\ln\frac{e^2 - 1}{2}$, the exact answer.
4. **Why bisection helps.** For a function whose derivative can't be inverted by formula, bisection still works, and the theorem guarantees there's something to find.

**Answer:** c = 1.161439, which is $\ln\frac{e^2 - 1}{2}$.
:::
:::

::: example
## Truncate $\int_1^\infty\frac{\ln x}{x^2}dx$ at B = 1000 and add the exact tail.

::: solution
1. **Integrate up to B.** The trapezoid rule on [1, 1000] with two million intervals gives 0.992092.
2. **Add the exact tail.** The tail beyond 1000 is
   $$\frac{\ln 1000 + 1}{1000} = 0.007908$$
   so the total is 0.99999998.
3. **Compare with the exact value.** The exact value is 1. Truncating alone leaves an error of 0.8%: slowly decaying integrands need their tails handled analytically, rather than by a larger B.

**Answer:** 0.992092 plus the tail 0.007908 gives 0.99999998, against the exact value 1.
:::
:::

::: check
given: a = 1 | 2; e = 0.1 | 0.5
answer: sqrt(a^2 + e) - a
tolerance: 0.5%

## What is the largest δ for $x^2$ at a = {a} with ε = {e}?

::: right
Right. Set by the right side: $\sqrt{a^2 + \varepsilon} - a$.
:::

::: misses
- [a - sqrt(a^2 - e)] That's the left side's room, which is larger.
- [any] Solve $(a + \delta)^2 = a^2 + \varepsilon$.
:::
:::

::: check
given: f = 24 | 720 | 40320
answer: exp(1)/f
tolerance: 0.5%

## The degree-n Taylor polynomial of $e^x$ at 0 is used at x = 1, where (n + 1)! = {f}. What is the Lagrange bound $\frac{e}{(n + 1)!}$ on its error?

::: right
Right. The bound falls factorially; the actual error is smaller still, by less than a factor of e.
:::

::: misses
- [1/f] The bound uses $M = \max e^\xi = e$ on [0, 1].
- [any] $\frac{e}{(n + 1)!}$.
:::
:::

::: check
kind: python

## Write `largest_delta(f, a, eps)`: bisect on δ in [0, 1] (100 steps), checking $\max\lvert f(x) - f(a)\rvert < \varepsilon$ on 2001 points of $[a - \delta, a + \delta]$. Set `d` for $x^2$ at a = 2, ε = 0.1.

```python starter
import numpy as np

def largest_delta(f, a, eps):
    return 0.0

d = largest_delta(lambda x: x**2, 2.0, 0.1)
print(d)
```

```python solution
import numpy as np

def largest_delta(f, a, eps):
    lo, hi = 0.0, 1.0
    for _ in range(100):
        m = (lo + hi) / 2
        xs = np.linspace(a - m, a + m, 2001)
        if np.max(np.abs(f(xs) - f(a))) < eps:
            lo = m
        else:
            hi = m
    return lo

d = largest_delta(lambda x: x**2, 2.0, 0.1)
print(d)
```

```python tests
import math
assert abs(d - (math.sqrt(4.1) - 2)) < 1e-9, f"The largest delta is sqrt(4.1) - 2 = 0.0248457; got {d}."
```

::: right
Right. 0.0248457, set by the right side of a.
:::
:::

::: check
kind: python

## Find by bisection the point c in (0, 2) where $e^c$ equals the chord slope $\frac{e^2 - 1}{2}$. Set `c`.

```python starter
import math

c = 1.0
print(c)
```

```python solution
import math

target = (math.exp(2) - 1) / 2
lo, hi = 0.0, 2.0
for _ in range(100):
    m = (lo + hi) / 2
    if math.exp(m) < target:
        lo = m
    else:
        hi = m
c = (lo + hi) / 2
print(c)
```

```python tests
import math
assert abs(c - math.log((math.e**2 - 1) / 2)) < 1e-12, f"c = ln((e^2 - 1)/2) = 1.161439; got {c}."
```

::: right
Right. c = 1.161439, slightly past the midpoint because $e^x$ is convex.
:::
:::

::: check
kind: python

## For n = 1 to 8, set `errs` to the actual errors of the degree-n Taylor polynomial of $e^x$ at x = 1, and `bounds` to the Lagrange bounds $\frac{e}{(n + 1)!}$.

```python starter
import math

errs = bounds = [0.0] * 8
print(errs, bounds)
```

```python solution
import math

errs = [abs(math.e - sum(1 / math.factorial(k) for k in range(n + 1))) for n in range(1, 9)]
bounds = [math.e / math.factorial(n + 1) for n in range(1, 9)]
print(errs, bounds)
```

```python tests
assert all(0 < e <= b for e, b in zip(errs, bounds)), "Every actual error should be positive and within its bound."
assert abs(errs[4] - 0.0016152) < 1e-6, f"With n = 5 the error is 0.0016152; got {errs[4]}."
assert all(b / e < 3 for e, b in zip(errs, bounds)), "The bound overestimates by less than e here."
```

::: right
Right. Each error is inside its bound, by a factor of less than e: the bound uses $e^1$ for $e^\xi$, the worst case.
:::
:::

::: check
kind: python

## Write `UL(n)` returning the upper and lower sums of $e^{-x}$ on [0, 1] with n equal strips. Set `n_needed` to the smallest n with U − L < $10^{-3}$.

```python starter
import numpy as np

def UL(n):
    return 1.0, 0.0

n_needed = 1
print(n_needed)
```

```python solution
import numpy as np

def UL(n):
    x = np.arange(n) / n
    U = np.sum(np.exp(-x)) / n
    L = np.sum(np.exp(-(x + 1 / n))) / n
    return U, L

n_needed = 1
while UL(n_needed)[0] - UL(n_needed)[1] >= 1e-3:
    n_needed += 1
print(n_needed)
```

```python tests
import math
U, L = UL(10)
assert abs(U - 0.6642533) < 1e-6 and abs(L - 0.6010412) < 1e-6, f"With 10 strips U = 0.66425 and L = 0.60104; got {U}, {L}."
assert n_needed == 633, f"U - L = (1 - 1/e)/n first drops below 1e-3 at n = 633; got {n_needed}."
```

::: right
Right. 633 strips, as $\frac{1 - e^{-1}}{n} < 10^{-3}$ predicts.
:::
:::

::: check
kind: python

## Compute $\int_1^{1000}\frac{\ln x}{x^2}dx$ with the trapezoid rule on 2 000 001 points (`trunc`), then add the exact tail $\frac{\ln 1000 + 1}{1000}$ (`total`).

```python starter
import math
import numpy as np

trunc = total = 0.0
print(trunc, total)
```

```python solution
import math
import numpy as np

x = np.linspace(1, 1000, 2000001)
y = np.log(x) / x**2
h = x[1] - x[0]
trunc = h * (np.sum(y) - (y[0] + y[-1]) / 2)
total = trunc + (math.log(1000) + 1) / 1000
print(trunc, total)
```

```python tests
assert abs(trunc - 0.992092) < 1e-5, f"The truncated integral is 0.99209; got {trunc}."
assert abs(total - 1) < 1e-6, f"With the tail the integral is 1; got {total}."
```

::: right
Right. 0.99209 truncated, and 1.0000000 with the exact tail added.
:::
:::

::: explain
## Why is the largest δ for $x^2$ set by the side where the function climbs faster?

::: model
Continuity at a asks that every x within δ of a have f(x) within ε of f(a). The function leaves the ε band first on whichever side it changes faster, because there it needs less distance to change by ε. For $x^2$ with a > 0, the slope to the right of a is larger than to the left, so the band's upper edge is reached sooner going right: at $\sqrt{a^2 + \varepsilon}$, a distance $\sqrt{a^2 + \varepsilon} - a$ away. A symmetric interval must fit the tighter side, so that distance is the largest δ. For functions that are steeper to the left, the left side sets it instead.
:::
:::

::: practice

::: check
given: a = 0.5 | 4; e = 0.2 | 0.05
answer: sqrt(a^2 + e) - a
tolerance: 0.5%

## Largest δ for $x^2$ at {a}, ε = {e}?

::: misses
- [any] $\sqrt{a^2 + \varepsilon} - a$.
:::
:::
:::
