AI Wiki中文/EN

Integration for expectations

积分与期望计算

Accumulate signed quantities, compare quadrature rules, and put the density into an expectation.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A rate becomes an amount when you add it over time

A server’s power use varies through the day. A single watt reading does not tell you its energy consumption; you need to accumulate power over time. Similarly, a probability density at one input does not tell you the expected loss of a model. You must combine losses across possible inputs, weighted by that density.

Integration describes this accumulation. Numerical quadrature approximates it from a limited set of function evaluations. They are related but different objects: the integral is defined by the mathematical function and domain; an approximation also depends on sample locations and a rule for combining them.

This chapter treats continuous real-valued functions on a finite interval. Begin with limits and continuity and derivatives. General measure-theoretic integration and high-dimensional Monte Carlo methods are separate topics.

From weighted sums to a limit

Split an interval from a to b, with a smaller than b, into n equal pieces of width h. Choose one point ξᵢ in each piece and add its function value times the piece’s width. For a continuous function, refining the partition gives the same limit regardless of these choices:

∫abf(x) dx=lim⁡n→∞∑i=1nf(ξi)h,h=b−an,ξi∈[a+(i−1)h,a+ih].\int_a^b f(x)\,dx=\lim_{n\to\infty}\sum_{i=1}^{n}f(\xi_i)h,\qquad h=\frac{b-a}{n},\quad \xi_i\in[a+(i-1)h,a+ih].

The integral is signed: values below zero contribute negatively. Total geometric area instead integrates |f|. For power in watts and time in hours, the result has units of watt-hours. Omitting the interval width changes both the quantity and its units. OpenStax §5.2 develops definite integrals from sums and explains signed accumulation.

The fundamental theorem connects integration with differentiation. If f is continuous and F is an antiderivative on the interval, then:

F′(x)=f(x)⟹∫abf(x) dx=F(b)−F(a).F'(x)=f(x)\quad\Longrightarrow\quad\int_a^b f(x)\,dx=F(b)-F(a).

Thus the integral of x² from 0 to 1 is 1/3, using F(x)=x³/3. The arbitrary constant cancels between endpoints. The theorem’s other direction says that the accumulated integral up to a variable endpoint differentiates back to the continuous integrand. See OpenStax §5.3.

Two practical rules, with different local approximations

Let xᵢ=a+ih. The composite trapezoidal rule joins neighboring sampled heights by straight lines. Simpson’s rule integrates a quadratic interpolant over each pair of intervals and requires even n:

Tn=h[f(x0)+f(xn)2+∑i=1n−1f(xi)],Sn=h3[f(x0)+f(xn)+4∑i=1i oddn−1f(xi)+2∑i=2i evenn−2f(xi)].T_n=h\left[\frac{f(x_0)+f(x_n)}{2}+\sum_{i=1}^{n-1}f(x_i)\right],\qquad S_n=\frac{h}{3}\left[f(x_0)+f(x_n)+4\sum_{\substack{i=1\\i\ \mathrm{odd}}}^{n-1}f(x_i)+2\sum_{\substack{i=2\\i\ \mathrm{even}}}^{n-2}f(x_i)\right].

The trapezoid weights follow by adding each interval’s width times the average of its endpoint heights: interior samples appear in two adjacent pieces. Simpson’s 1,4,1 weights come from integrating the three interpolation basis polynomials across a pair; interior even-index endpoints are then shared by adjacent pairs. OpenStax’s numerical integration chapter derives these rules.

With a bounded continuous second derivative, trapezoidal absolute error is at most M₂(b−a)³/(12n²), where M₂ bounds |f″|. With a bounded continuous fourth derivative, Simpson error is at most M₄(b−a)⁵/(180n⁴). These are conditional bounds, not promises for arbitrary noisy or discontinuous inputs. Simpson’s rule is exact for polynomials of degree at most three in exact arithmetic.

An expectation uses a density, not an unweighted average

For a continuous random variable with density p on [a,b], the expected value of g is the integral of g(x)p(x), provided the expectation is well defined. Our example takes p(x)=2x on [0,1]; it is nonnegative and integrates to one. Consequently:

E[X2]=∫01x2(2x) dx=12.\mathbb E[X^2]=\int_0^1 x^2(2x)\,dx=\frac12.

Integrating x² alone would give 1/3, which corresponds to a uniform density on this interval. Choosing the wrong weight can yield a numerically accurate answer to the wrong probability question.

Check approximation error against an exact answer

Run this complete Python 3.12 standard-library program. It accepts rational endpoints, a trusted callable returning integers or fractions, and 1–1000 subdivisions. It supports reversed endpoints, for which the integral changes sign. Equal endpoints return zero without evaluating the callable. Invalid method names and odd Simpson counts are rejected.

from fractions import Fraction as F


def integrate(f,a,b,n,method='trapezoid'):
    if type(n) is not int or not 1 <= n <= 1000:
        raise ValueError('integer subdivision count in [1,1000] required')
    if method not in ('trapezoid','simpson') or (method == 'simpson' and n % 2):
        raise ValueError('Simpson requires even n; unknown methods are rejected')
    if type(a) not in (int,F) or type(b) not in (int,F):
        raise ValueError('integer or Fraction endpoints required')
    a,b=F(a),F(b)
    if a == b:
        return F(0)
    h=(b-a)/n
    total=F(0)
    for i in range(n+1):
        value=f(a+i*h)
        if type(value) not in (int,F):
            raise ValueError('integrand must return an integer or Fraction')
        if method == 'trapezoid':
            weight=F(1,2) if i in (0,n) else F(1)
        else:
            weight=F(1) if i in (0,n) else F(4 if i % 2 else 2)
        total+=weight*value
    return h*total/(3 if method == 'simpson' else 1)


if __name__ == '__main__':
    square=lambda x:x*x
    for n in (2,4,8):
        trap=integrate(square,0,1,n)
        simp=integrate(square,0,1,n,'simpson')
        assert trap-F(1,3) == F(1,6*n*n)
        assert simp == F(1,3)
        print('n='+str(n),'trapezoid='+str(trap),'Simpson='+str(simp))
    expectation=integrate(lambda x:2*x*x*x,0,1,4,'simpson')
    print('E[X^2] under density 2x:',expectation)
    assert expectation == F(1,2)

Output:

n=2 trapezoid=3/8 Simpson=1/3
n=4 trapezoid=11/32 Simpson=1/3
n=8 trapezoid=43/128 Simpson=1/3
E[X^2] under density 2x: 1/2

For x² on [0,1], the trapezoidal result is exactly 1/3+1/(6n²). The error falls by a factor of four when n doubles. Simpson already gives 1/3; for the expectation it integrates the cubic 2x³ exactly and gives 1/2. These observations agree with both antiderivatives and the rules’ polynomial behavior.

Each rule makes n+1 evaluations for unequal endpoints, uses O(n) arithmetic operations and a constant number of live accumulators. Fraction arithmetic has variable bit cost; it is chosen here to separate quadrature error from floating-point rounding. This is not a high-performance integration library.

More points help only when the model of error fits

A narrow spike can fall between every sampled point. A discontinuity can violate the smoothness assumptions behind a high-order error bound. If only noisy measurements are available, finer interpolation does not remove measurement error. Adaptive quadrature allocates evaluations where an error estimate suggests they are useful, but estimates also need assumptions and failure checks.

Infinite intervals and singular integrands require improper-integral analysis or transformations; this code samples finite endpoints and is not designed for those cases. Repeated integrals over many dimensions suffer from growing grid sizes. Monte Carlo integration uses random sampling and a different error analysis.

An indefinite integral denotes a family of antiderivatives, while a definite integral is an accumulated value. An antiderivative need not have a convenient elementary expression. A numerical rule approximates the accumulated value without requiring one.

Check the weight and the error separately

  1. What is the trapezoidal error for x² on [0,1] with n=4?

Answer 1: It is 1/(6×16)=1/96. The estimate is 11/32, while the exact integral is 1/3.

  1. Why does Simpson require an even subdivision count in this implementation?

Answer 2: Each quadratic interpolation piece spans a pair of adjacent intervals. An odd count leaves one unmatched interval, so the stated composite formula does not apply unchanged.

  1. For density p(x)=2x on [0,1], does integrating x² alone give E[X²]?

Answer 3: No. Multiply by the density: integrate 2x³ to obtain 1/2. The unweighted integral 1/3 answers the uniform-density problem.

  1. What is the integral of x from −1 to 1, and what is the geometric area between the graph and the axis?

Answer 4: The signed integral is zero because opposite contributions cancel. The area is the integral of |x|, which equals one.

Choose a quadrature method for the available information

The cited OpenStax sections cover the mathematical definition, the fundamental theorem and deterministic quadrature. The rational program keeps the rule’s error visible and avoids attributing an approximation difference to the wrong source.

Continue with expectation and variance to use integrals in probability, or with Monte Carlo integration for sampling-based computation. A useful extension is x⁴: compare Simpson’s approximation with the antiderivative value 1/5, then test the fourth-order error decrease before moving to a function with a kink.

Make a prediction, then check

For density p(x)=2x on [0,1], what integrand gives E[X²]?

Choose one answer

Learning objectives

  • Distinguish an integral from its numerical approximation.
  • Evaluate a density-weighted expectation and check known quadrature errors.

Prerequisites & connections

Explore related knowledge →

References

  1. Calculus Volume 1 — 5.2 The Definite Integral
    Gilbert Strang; Edwin Herman; OpenStax · 2016
  2. Calculus Volume 1 — 5.3 The Fundamental Theorem of Calculus
    Gilbert Strang; Edwin Herman; OpenStax · 2016
  3. Calculus Volume 2 — 3.6 Numerical Integration
    Gilbert Strang; Edwin Herman; OpenStax · 2016

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: primary-source locations, explicit assumptions, derivations, literal or exact computational checks, and bilingual review; not independent human or second-agent peer review.

  • Single-agent authored technical review: source locations, stated domains and assumptions, derivations, literal or exact reference cases and matching bilingual programs/exercises. Not independent human or second-agent peer review.
  • Four focused tests passed on CPython 3.12.4. Exact Fraction examples are used except for the explicitly floating-point damped Newton experiment. Strict bilingual MDX/KaTeX rendering gives four equations, six anchors and four answers per language; repository publication checks are recorded separately.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.