Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lecture 5 · Approximation, Errors, and Quadrature

Block 2 · Week 3

San Diego State University

Approximation, errors, and quadrature

From continuous mathematics to finite calculations

A computer stores finitely many digits and evaluates finitely many operations. Calculus defines derivatives through limits and integrals through continuous accumulation. Today we connect these descriptions.

The through-line

Jump to: Numbers · Taylor · Tolerances · Quadrature

  1. Represent a number.

  2. Approximate a function locally.

  3. Identify the omitted terms.

  4. Measure an error and choose a comparison tolerance.

  5. Approximate an integral with a sum.

State the approximation before interpreting its numerical error.

Today’s question

How do finite representations and finite approximations affect the calculations we make from continuous mathematics?

By the end of class, you should be able to:

  • distinguish representation, arithmetic rounding, and truncation;

  • use a Taylor remainder to explain a leading error term;

  • explain why a smaller step can hurt a finite difference;

  • choose atol and rtol for a stated comparison; and

  • implement left-rectangle quadrature and check its first-order prediction.

I · Numbers and operations have finite precision

What changes between a real number on paper and a number stored in a computer?

Goals

  • distinguish representable values from rounded approximations;

  • relate absolute spacing to the scale of a number; and

  • separate representation and arithmetic errors from method truncation.

Predict · which sums are exactly represented?

Python stores these numbers as binary fractions, built from 1/2,1/4,1/8,…1/2, 1/4, 1/8, \ldots. Some fit exactly; others must be rounded.

Predict: will both of these print True?

== checks exact equality. It does not allow a small discrepancy.

Explain · why False, then True?

Why False?

Just as 1/3=0.3333…1/3=0.3333\ldots repeats in decimal, 0.1 and 0.2 repeat in binary. Python stores rounded approximations.

Adding them and rounding the result produces a slightly different stored number from entering 0.3 directly:

== therefore returns False.

Why True?

These fractions have exact, finite binary representations:

0.5=12,0.25=14,0.5=\frac12,\qquad 0.25=\frac14,
0.75=12+14.0.75=\frac12+\frac14.

Their representations and this addition require no rounding. The stored sum equals the stored value of 0.75 exactly.

== therefore returns True.

Spacing depends on the scale of the number

value=1.0e+00, next-float spacing=2.220e-16
value=1.0e+08, next-float spacing=1.490e-08
binary64 epsilon: 2.220446049250313e-16

Machine epsilon is the gap from 1.0 to the next larger binary64 number. It is not a universal absolute error or a guarantee about a calculation.

Explain: why would one fixed absolute tolerance mean different things at scales of 1 and 108?

Three sources of numerical discrepancy

SourceExampleWhat we can change
RepresentationStore a decimal fraction in binaryPrecision; scaling when appropriate
Rounding during arithmeticSubtract nearly equal approximationsAlgebraic formulation; precision
Truncation of a mathematical procedureReplace a derivative by a finite differenceStep size; approximation order

Measurement uncertainty and model error are additional questions. They are not automatically measured by any of these numerical errors.

An accurate implementation can still calculate an inadequate model.

Reference · finite precision

PatternWhat it reveals
np.finfo(np.float64).epsSpacing immediately above 1 for binary64
np.spacing(value)Local floating-point spacing
f"{value:.17g}"More digits than a short default display may show
np.isfinite(value)Whether the value is neither infinity nor nan

Rule: the precision of a representation is not the accuracy of a calculation.

II · Taylor expansion describes a local approximation

How much of a function can we reconstruct from its value and derivatives at one point?

Goals

  • construct constant, linear, and quadratic local approximations;

  • interpret the remainder and an order statement;

  • predict an error ratio under refinement; and

  • derive a forward difference and explain its rounding tradeoff.

Build the polynomial one derivative at a time

Near x0x_0, write x=x0+hx=x_0+h. Taylor’s theorem gives

f(x0+h)=f(x0)+hf′(x0)+h22!f′′(x0)+⋯+hmm!f(m)(x0)+Rm+1.f(x_0+h)=f(x_0)+h f'(x_0)+\frac{h^2}{2!}f''(x_0) +\cdots+\frac{h^m}{m!}f^{(m)}(x_0)+R_{m+1}.

Each derivative describes another aspect of the local shape.

  • Constant: the value at the expansion point.

  • Linear: value and slope.

  • Quadratic: value, slope, and curvature.

The equality includes Rm+1R_{m+1}, the part the polynomial does not capture. Dropping the remainder gives an approximation, f(x0+h)≈Pm(h)f(x_0+h)\approx P_m(h).

For the remainder formula used here, assume ff has continuous derivatives through order m+1m+1 on the interval between x0x_0 and x0+hx_0+h.

Why these coefficients reproduce the local shape

Start with an unknown polynomial in the displacement hh:

Pm(h)=a0+a1h+a2h2+⋯+amhm.P_m(h)=a_0+a_1h+a_2h^2+\cdots+a_mh^m.

Choose its derivatives at h=0h=0 to match those of ff at x0x_0:

MatchConditionCoefficient
ValuePm(0)=f(x0)P_m(0)=f(x_0)a0=f(x0)a_0=f(x_0)
SlopePm′(0)=f′(x0)P_m'(0)=f'(x_0)a1=f′(x0)a_1=f'(x_0)
CurvaturePm′′(0)=f′′(x0)P_m''(0)=f''(x_0)2a2=f′′(x0)2a_2=f''(x_0)
Derivative k≤mk\le mPm(k)(0)=f(k)(x0)P_m^{(k)}(0)=f^{(k)}(x_0)k!ak=f(k)(x0)k!a_k=f^{(k)}(x_0)

Why divide by a factorial?

Differentiating hkh^k exactly kk times produces k!k!. That is why the coefficient is f(k)(x0)/k!f^{(k)}(x_0)/k!.

Matching at one point does not make the functions identical everywhere. Taylor’s theorem tells us how to express the remaining difference.

Work out a local model for the exponential

For f(x)=exf(x)=e^x at x0=0x_0=0, every derivative equals 1:

P0(h)=1,P1(h)=1+h,P2(h)=1+h+h22.P_0(h)=1,\qquad P_1(h)=1+h,\qquad P_2(h)=1+h+\frac{h^2}{2}.

Compare the results: which approximation is best at these offsets? Why does this not guarantee the same accuracy one unit away?

h=0.50: errors P0, P1, P2 = [0.64872127 0.14872127 0.02372127]
h=0.10: errors P0, P1, P2 = [0.10517092 0.00517092 0.00017092]
h=0.01: errors P0, P1, P2 = [1.00501671e-02 5.01670842e-05 1.67084168e-07]

See the value, slope, and curvature

The exponential and its constant, linear, and quadratic Taylor polynomials agree at zero and separate away from zero. The quadratic tracks the curvature most closely near zero. Line styles and labels distinguish the curves.

Each polynomial uses information at the same expansion point, x0=0x_0=0.

Explain: what feature does the quadratic capture that the line cannot?

The remainder tells us what we omitted

For some ξ\xi between x0x_0 and x0+hx_0+h,

Rm+1=f(m+1)(ξ)(m+1)!hm+1.R_{m+1}=\frac{f^{(m+1)}(\xi)}{(m+1)!}h^{m+1}.

If the derivative is bounded there, the remainder is O(hm+1)O(h^{m+1}). This means there is a constant CC such that

∣Rm+1∣≤C∣h∣m+1\lvert R_{m+1}\rvert\le C\lvert h\rvert^{m+1}

for sufficiently small hh in the stated region.

This is a finite polynomial plus a remainder. We do not need an infinite Taylor series to converge to use this local result.

More terms: accuracy costs arithmetic

For ehe^h with 0≤h≤r0\le h\le r, every derivative is bounded by ere^r, so

∣eh−Pm(h)∣≤erhm+1(m+1)!.|e^h-P_m(h)|\le e^r\frac{h^{m+1}}{(m+1)!}.

For a fixed positive hh, adding terms reduces the truncation error in this example. Farther from the expansion point, more terms are needed for the same absolute accuracy.

Read the plot · how many terms are enough?

Absolute exponential approximation error decreases from degree zero through eight. At every degree the error at h equals two is larger than at h equals one half; circles and squares distinguish the two curves.

Both approximations use derivatives at zero. More terms improve these results, but evaluating those terms requires additional operations.

Count the work before claiming a speed improvement

For this exponential polynomial, reuse the previous term:

term = total = 1.0           # Start with the constant term, P0 = 1.
for k in range(1, m + 1):    # Add terms 1 through m; stop is excluded.
    term = term * h / k      # One multiplication and one division.
    total = total + term     # One addition accumulates the next term.

Reference · operation count and accuracy

Degree mmTerms retainedArithmetic operations in this loop
236
4512
8924

This counts scalar arithmetic, excluding loop overhead; it is not a timing measurement. For a general function, obtaining derivatives can add substantial cost. Library functions such as np.exp use their own optimized algorithms.

Decision: choose enough terms for a justified error target. More terms do not always improve a general function’s approximation at a fixed point, and floating-point rounding can eventually limit improvement even here.

An order predicts a refinement ratio

If the leading error is nonzero and dominates,

E(h)≈Chq,E(h/2)≈E(h)2q.E(h)\approx C h^q,\qquad E(h/2)\approx \frac{E(h)}{2^q}.
Leading order qqError after halving hh
1Approximately one half
2Approximately one quarter
4Approximately one sixteenth

An O(hq)O(h^q) bound alone does not establish an exact slope. Cancellation can remove a leading term, and rounding can obscure it.

Apply the rule: if a first-order error is 0.02, what error do you expect after halving hh, while the same leading term dominates?

Taylor expansion gives a finite difference

Start with

f(x+h)=f(x)+hf′(x)+h22f′′(x)+O(h3).f(x+h)=f(x)+h f'(x)+\frac{h^2}{2}f''(x)+O(h^3).

Subtract f(x)f(x) and divide by h≠0h\ne0:

f(x+h)−f(x)h=f′(x)+h2f′′(x)+O(h2).\frac{f(x+h)-f(x)}{h} =f'(x)+\frac{h}{2}f''(x)+O(h^2).

The forward difference has a leading truncation error of order hh when f′′(x)≠0f''(x)\ne0. We can calculate it without taking a limit in code.

Predict: does this imply that the smallest representable step is best?

Run · smaller steps eventually stop helping

For f(x)=exf(x)=e^x at x=0x=0, the exact derivative is 1.

Read the finite-difference results

h=1e-01: derivative=1.05170918, error=5.171e-02
h=1e-04: derivative=1.00005000, error=5.000e-05
h=1e-07: derivative=1.00000005, error=4.943e-08
h=1e-10: derivative=1.00000008, error=8.274e-08
h=1e-13: derivative=0.99920072, error=7.993e-04
h=1e-16: derivative=0.00000000, error=1.000e+00

Interpret · where does refinement stop helping?

On logarithmic axes, the forward-difference error decreases as h is reduced from one tenth, then becomes irregular and increases for very small h. A dashed h over two line shows the truncation prediction.

Read toward the left for smaller steps. Exact printed values depend on the floating-point implementation; the truncation prediction does not include rounding.

Why two small errors can produce a larger one

The numerator subtracts values close to 1. Their absolute representation and evaluation errors may be small compared with 1, but large compared with the small difference. Division by hh amplifies that discrepancy.

A useful local model for this example is

E(h) of size C1h+C2ϵmachh.E(h)\ \text{of size}\ C_1h+C_2\frac{\epsilon_{\rm mach}}{h}.

The constants depend on the function, point, and implementation. This model explains competing trends; it does not give a universal best step size.

For this particular expression, np.expm1(h) / h avoids subtracting 1 from a rounded exponential. Stable algebra can change the rounding behavior while leaving the truncation order unchanged.

Reference · Taylor approximation and error order

StatementInterpretation
f(x0+h)=Pm(h)+Rm+1f(x_0+h)=P_m(h)+R_{m+1}An approximation plus its remainder
Rm+1=O(hm+1)R_{m+1}=O(h^{m+1})A local bound under the stated smoothness conditions
E(h)≈ChqE(h)\approx Ch^qA dominant, nonzero error term predicts a refinement ratio
E(h)/E(h/2)≈2qE(h)/E(h/2)\approx2^qAn observable to compare with that prediction

Rule: state the region and assumptions before interpreting an observed order.

III · Measure the error before deciding what is acceptable

What does it mean for a result to agree with a reference closely enough?

Goals

  • compute absolute and relative discrepancies;

  • state the units and roles of atol and rtol;

  • handle a zero or very small reference deliberately; and

  • justify a tolerance independently of whether a test passes.

Absolute and relative errors answer different questions

For a computed value QQ and a reference Q⋆Q_\star,

Eabs=∣Q−Q⋆∣,Erel=∣Q−Q⋆∣∣Q⋆∣(Q⋆≠0).E_{\rm abs}=\lvert Q-Q_\star\rvert,\qquad E_{\rm rel}=\frac{\lvert Q-Q_\star\rvert}{\lvert Q_\star\rvert} \quad(Q_\star\ne0).
  • Absolute error has the same units as QQ.

  • Relative error is dimensionless; multiply by 100 for percent error.

  • At a zero reference, relative error is undefined.

  • Against an approximate reference, these are discrepancies that also contain the reference’s error.

A tolerance is an acceptance criterion. It does not measure or reduce error.

atol and rtol state two scales of agreement

For finite values, NumPy evaluates

∣Q−Q⋆∣≤atol⏟absolute allowance+rtol ∣Q⋆∣⏟scale-dependent allowance.\lvert Q-Q_\star\rvert\le \underbrace{\mathrm{atol}}_{\text{absolute allowance}} +\underbrace{\mathrm{rtol}\,\lvert Q_\star\rvert}_{\text{scale-dependent allowance}}.
np.isclose(computed, reference, rtol=relative_allowance,
           atol=absolute_allowance)

atol has the quantity’s units. rtol is a fraction: 0.01 means 1%. Put the reference second: NumPy uses it to set the relative scale.

With both nonzero, NumPy adds the allowances. Agreement need not satisfy each allowance separately.

See the tolerance as an acceptance region

Read the figure: with atol=0.1 cm and rtol=0.1, how much discrepancy is allowed at a reference of zero? At a reference of 2 cm?

A shaded acceptance region includes zero residual and widens from plus or minus 0.1 cm at a zero reference to plus or minus 0.4 cm at references of plus or minus 3 cm. Dashed lines mark the absolute allowance.

NumPy accepts finite comparisons inside the shaded region, including its boundary.

Open full-size figure.

Interpret the tolerance

At zero: 0.1 cm. At 2 cm: 0.1+0.1(2)=0.30.1+0.1(2)=0.3 cm. These tolerances are comparison choices, not floating-point properties.

Explain: does passing this comparison tell us whether a model describes its physical system correctly?

Predict · the same absolute error at different scales

Suppose our stated criterion is relative agreement within one part in a million, with no separate absolute allowance.

Predict: which comparisons pass? State the allowed error for each reference.

Results · the same absolute error at different scales

absolute error: [0.1 0.1]
allowed error: [1.e-06 1.e+00]
accepted: [False  True]

Explain: why does one comparison fail and the other pass? Would changing the tolerance change either computed value?

Near zero, the absolute scale matters

Suppose an example calculation has an independently chosen absolute accuracy target of 10-8 cm. Compare its residual with zero:

relative only: False
absolute target: True

No finite relative tolerance permits a nonzero discrepancy against exactly zero when atol=0. Choose an absolute scale from the question being tested.

The 10-8 cm here is a stated example target, not a universal recommendation.

A default absolute tolerance can hide a large relative error

These example fluxes differ by 100% of the reference value:

NumPy defaults: True
stated 1% target: False

NumPy’s default atol=1e-8 is larger than either value in these units. Always check the tolerance against the scale and units of the calculation.

Source: NumPy isclose documentation.

Similar comparison functions have different rules

For finite scalar values aa and bb:

FunctionPermitted discrepancy
np.isclose(a, b, rtol=r, atol=t)t+r∣b∣t+r\lvert b\rvert
math.isclose(a, b, rel_tol=r, abs_tol=t)max⁡(t,rmax⁡(∣a∣,∣b∣))\max(t,r\max(\lvert a\rvert,\lvert b\rvert))

Lecture 1 used math.isclose; today we use NumPy for arrays. The formulas are different, so do not treat a name change as the whole conversion.

np.isclose returns one Boolean per element. np.allclose asks whether all elementwise comparisons pass. Ensure arrays have the intended shapes before comparing: NumPy can broadcast them.

Sources: NumPy · Python math.isclose.

Choose a tolerance from the claim

  1. Identify the reference and its accuracy.

  2. State the units and whether an absolute or fractional discrepancy matters.

  3. Use a method error bound, a convergence study, or a stated accuracy target.

  4. Set the tolerance before inspecting whether the result passes.

  5. If it fails, investigate the calculation and the criterion.

Check that quantities expected to be finite are finite. A comparison is not a substitute for that contract.

Explain: if a method is first order, does asking for rtol=1e-12 make it more accurate? What would you actually need to change?

Reference · tolerances and error measurements

Quantity or choiceMeaning
abs(computed - reference)Absolute discrepancy, in the quantity’s units
Absolute discrepancy divided by abs(reference)Fractional discrepancy for a nonzero reference
rtol=0.0Only the absolute allowance contributes
atol=0.0Only the relative allowance contributes
Both nonzero in np.iscloseNumPy adds the absolute and reference-scaled allowances

Rule: a tolerance expresses a claim. Increasing it does not improve the result.

IV · Quadrature replaces an integral with a finite sum

How can local function approximations give a numerical value for an integral?

Goals

  • distinguish the interval, panels, nodes, heights, and weights;

  • implement a callable-based left-rectangle rule;

  • connect local area error to composite error; and

  • compare computed errors with a ratio prediction and a bound.

Approximate one panel, then add the areas

Consider a fixed interval [a,b][a,b], with a<ba<b. Divide it into nn equal panels:

h=b−an,xi=a+ih,i=0,1,…,n.h=\frac{b-a}{n},\qquad x_i=a+ih,\qquad i=0,1,\ldots,n.

There are nn panels and n+1n+1 boundary points.

On panel [xi,xi+1][x_i,x_{i+1}], use the constant approximation f(x)≈f(xi)f(x)\approx f(x_i):

∫xixi+1f(x) dx≈hf(xi).\int_{x_i}^{x_{i+1}} f(x)\,dx\approx h f(x_i).

Adding the panel contributions gives the left-rectangle rule:

Ln=h∑i=0n−1f(xi).L_n=h\sum_{i=0}^{n-1}f(x_i).

Explain · which area is missing?

For f(x)=sin⁡xf(x)=\sin x on [0,π/2][0,\pi/2], the function is increasing and the exact integral is 1. Use the rectangles to explain the sign of Ln−1L_n-1.

Six left-endpoint rectangles lie below the increasing sine curve between zero and pi over two. Dots mark the sampled left endpoints, and the rightmost boundary is not a sampled height.

The first rectangle has height zero. That panel still contributes to the integral, which explains part of the underestimate.

Build the nodes before the function

panels: 6 sampled heights: 6
left endpoints: [0.         0.26179939 0.52359878 0.78539816 1.04719755 1.30899694]
rectangle sum: 0.8633821943925831

np.arange(n) supplies the integers 0 through n-1. The last sample is b−hb-h, not bb.

Explain: why would np.linspace(a, b, n) give the wrong node spacing here?

One function implements the rule

width = (b - a) / n
nodes = a + width * np.arange(n)
return float(width * np.sum(f(nodes)))
  1. Set the panel width.

  2. Sample the left endpoints.

  3. Add height × width.

The complete function on the next slide also validates n.

Contract: finite scalar limits; f accepts and returns finite arrays of matching shape. n is a positive integer; booleans are excluded.

Reference · rectangle implementation

0.9921254566056329

Why use isinstance for input checks?

isinstance(value, type) asks whether a value belongs to a type, including its subclasses. A tuple of types accepts any of the listed types.

True
False
True
True

A panel count describes a number of intervals. The rule accepts positive integers and rejects True, 6.0, and 6.5 under its stated contract. Silently applying int(n) could turn 6.5 into 6 and change the requested grid.

The first check rejects unsuitable types; n <= 0 rejects unsuitable values. raise ValueError(...) stops the calculation and tells the caller which input requirement was violated. This example checks n; finite limits and finite, matching integrand arrays remain caller preconditions here.

Passing a function is different from calling one

ExpressionWhat it supplies
np.sinA callable: the rule can choose where to evaluate it
np.sin(nodes)Values at nodes already chosen
rectangle(np.sin, a, b, n)A quadrature calculation using the sine function

The rule owns the grid. The callable owns the mathematical function.

Predict: what must change inside rectangle to integrate exe^x instead?

Reuse the rule with another function

Nothing inside rectangle changes. Pass a different callable and interval.

sine: 0.9921254566056329
exponential: 1.7097047383081225

Taylor expansion explains the rectangle error

Within one panel, put x=xi+sx=x_i+s with 0≤s≤h0\le s\le h:

f(xi+s)=f(xi)+sf′(xi)+O(s2).f(x_i+s)=f(x_i)+s f'(x_i)+O(s^2).

Integrate each term:

∫xixi+hf(x) dx=hf(xi)+h22f′(xi)+O(h3).\int_{x_i}^{x_i+h}f(x)\,dx =h f(x_i)+\frac{h^2}{2}f'(x_i)+O(h^3).

The rectangle retains the first term. Its one-panel error is O(h2)O(h^2). For an increasing function, the missing leading area is positive.

One-panel error and whole-interval error differ

The interval length b−ab-a stays fixed while n=(b−a)/hn=(b-a)/h increases. If panel errors are uniformly bounded by Ch2C h^2, their sum is bounded by

nCh2=C(b−a)h.n C h^2=C(b-a)h.

Thus the composite left-rectangle rule has an O(h)O(h) error bound.

We can replace the unspecified constant CC by a bound on the slope. The next slide derives that bound for any continuously differentiable ff on [a,b][a,b].

Derive a bound for any smooth integrand

Assume a<ba<b and ∣f′(x)∣≤M1|f'(x)|\le M_1 throughout [a,b][a,b]. The mean value theorem bounds the change in height inside panel ii:

∣f(xi+s)−f(xi)∣≤M1s,0≤s≤h.|f(x_i+s)-f(x_i)|\le M_1s,\qquad 0\le s\le h.

The panel’s signed area error is the integral of that height difference:

Ei=∫0h[f(xi+s)−f(xi)] ds.E_i=\int_0^h[f(x_i+s)-f(x_i)]\,ds.

Take the absolute value, bound the integrand, and integrate:

∣Ei∣≤∫0h∣f(xi+s)−f(xi)∣ ds≤∫0hM1s ds=M1h22.|E_i|\le\int_0^h|f(x_i+s)-f(x_i)|\,ds \le\int_0^h M_1s\,ds=\frac{M_1h^2}{2}.

The factor 1/21/2 is the area of a triangle with base hh and height M1hM_1h.

Sum the panel bounds

Adding the absolute panel bounds gives

∣I−Ln∣=∣∑i=0n−1Ei∣≤∑i=0n−1∣Ei∣≤nM1h22=(b−a)22nM1.\lvert I-L_n\rvert=\left|\sum_{i=0}^{n-1}E_i\right| \le\sum_{i=0}^{n-1}|E_i|\le\frac{nM_1h^2}{2} =\frac{(b-a)^2}{2n}M_1.

These statements concern quadrature error in exact arithmetic. A numerical test must also allow for relevant floating-point effects.

Choose a panel count from an error target

For a requested absolute quadrature error τ>0\tau>0, it is sufficient that

M1(b−a)22n≤τ⟹n≥M1(b−a)22τ.\frac{M_1(b-a)^2}{2n}\le\tau \quad\Longrightarrow\quad n\ge\frac{M_1(b-a)^2}{2\tau}.

Choose a positive integer:

nsufficient=max⁡(1,⌈M1(b−a)22τ⌉).n_{\rm sufficient}=\max\left(1, \left\lceil\frac{M_1(b-a)^2}{2\tau}\right\rceil\right).

The ceiling rounds upward. This gives a sufficient count, not necessarily the smallest count that works: the bound allows the largest slope on every panel and ignores cancellation between panel errors.

This requires a justified derivative bound. Sampling f′f' at a few points does not prove that no larger slope occurs between them. Floating-point error is a separate contribution to the total error budget.

Run · test the first-order prediction

n= 20: estimate=0.9602160, error=3.978e-02, ratio=—
n= 40: estimate=0.9802365, error=1.976e-02, ratio=2.013
n= 80: estimate=0.9901504, error=9.850e-03, ratio=2.007
n=160: estimate=0.9950832, error=4.917e-03, ratio=2.003

Compare En/E2nE_n/E_{2n} with 2. One accurate answer would not show this pattern.

Explain: why would changing the integrand change the error magnitude even if the leading order stayed the same?

Use the error bound to choose an absolute tolerance

For sine on [0,π/2][0,\pi/2], f′(x)=cos⁡xf'(x)=\cos x, so M1=1M_1=1 and b−a=π/2b-a=\pi/2:

M1(b−a)22n=1⋅(π/2)22n=π28n.\frac{M_1(b-a)^2}{2n} =\frac{1\cdot(\pi/2)^2}{2n}=\frac{\pi^2}{8n}.

At n=100n=100,

∣I−L100∣≤π28(100)≈0.01234.\lvert I-L_{100}\rvert\le\frac{\pi^2}{8(100)}\approx0.01234.

Check the sine estimate against its bound

observed error: 0.007874543394367106
theoretical bound: 0.012337005501361697
within bound: True

The measured error is below the bound; rounding is much smaller here. Passing checks this example, not the general theorem.

Compute a sufficient panel count

sufficient panels for target 0.01: 124

The ceiling rounds upward: 124 panels suffice for this quadrature bound.

Reference · left-rectangle quadrature

ComponentExpression
Panel widthwidth = (b - a) / n
Left endpointsnodes = a + width * np.arange(n)
Heightsf(nodes)
Weighted sumwidth * np.sum(f(nodes))
Expected leading composite order1 for a nonvanishing leading term and a smooth integrand

Rule: the integrator selects the grid; the callable supplies the function values.

Same panels, different rectangle heights

Keep h=(b−a)/nh=(b-a)/n and the same panel boundaries. Change only where each height is sampled, with i=0,…,n−1i=0,\ldots,n-1:

RuleSample locationComposite sum
Lefta+iha+ihLn=h∑if(a+ih)L_n=h\sum_i f(a+ih)
Righta+(i+1)ha+(i+1)hRn=h∑if(a+(i+1)h)R_n=h\sum_i f(a+(i+1)h)
Midpointa+(i+12)ha+(i+\tfrac12)hMn=h∑if(a+(i+12)h)M_n=h\sum_i f(a+(i+\tfrac12)h)

Compare left, right, and midpoint rectangles

Three panels show six rectangles on the same sine curve from zero to pi over two. Circles, squares, and triangles mark samples on the curve at left endpoints, right endpoints, and midpoints. Left rectangles lie below the curve, right rectangles lie above it, and midpoint rectangles cross it. Titles give each area estimate; the exact integral is one.

All three rules use six heights. The rectangles retain the same bases; moving the sample changes their heights and the estimated area.

What changes when we move the sample?

For an increasing function and a<ba<b,

Ln≤I≤Rn,Rn−Ln=h[f(b)−f(a)].L_n\le I\le R_n,\qquad R_n-L_n=h[f(b)-f(a)].

The sum in the difference telescopes: interior samples cancel, leaving only the endpoint values. For a decreasing function, the inequalities reverse.

Predict · which side is the midpoint area on?

The midpoint rule cancels the linear contribution about each panel’s center, so its composite error is O(h2)O(h^2) when the second derivative is bounded. It need not lie on the same side of the integral as the left rule.

Predict: sine is concave down on this interval. Does midpoint sampling underestimate or overestimate its area?

Explain the midpoint estimate

A tangent at each midpoint lies above the curve, and its integral over the symmetric panel equals the midpoint rectangle area: here the midpoint rule overestimates.

Next lecture, connecting endpoint heights gives trapezoids. In fact, Tn=(Ln+Rn)/2T_n=(L_n+R_n)/2 on this uniform grid. We will derive why that average also improves the order.

Documentation for the next question

ResourceUse it for
NumPy finfoFloating-point representation limits
NumPy iscloseExact tolerance semantics
NumPy expm1Stable evaluation near zero
Python isinstanceType checks, tuples of types, and subclasses
NumPy arange and absArray indices and elementwise absolute values

Use the course readings for derivations and worked examples. Use official API documentation to check parameter meanings, assumptions, and return values.

When a comparison surprises you, print the discrepancy and the allowed discrepancy before changing either tolerance.

Exit check

  1. What is the difference between truncation error and rounding error?

  2. Why can reducing hh hurt a forward difference?

  3. Against a zero reference, which tolerance sets the allowed discrepancy?

  4. Why is a one-panel O(h2)O(h^2) error consistent with a composite O(h)O(h) error?

  5. What should happen to a first-order error when the panel count doubles?

Use the mechanism in each answer, not only the name of the error.

Carry forward

Next class: replace each constant panel approximation with a line, then a quadratic. We will organize the rectangle rule in a module and test it on sin⁡x\sin x using pytest.

Project 2 uses these ideas to build and assess numerical integrators. The assignment brief specifies the deliverables; today’s rule and error comparison give you a starting point.

Reading guide in Numerical Methods: Foundations, Part 1, “Forward Difference”; Part 2, the absolute/relative error and tolerance discussions; Part 3, “Taylor polynomial and remainder.” In Roots and Quadrature, Part 2, review the rectangle-rule section. The longer chapters are references; the other methods are not preparation for today’s rectangle implementation.