MATLAB Scientific Academy
INTERMEDIATE · 25 min

Estimate an integral numerically

Learn how a computer approximates a continuous area using discrete samples, and why sampling resolution matters.

What you will learn

  • Understand the trapezoidal rule.
  • Compare a numerical estimate with a known result.
  • Interpret the effect of sample count on numerical error.

The concept

Numerical integration estimates the area under a curve. The trapezoidal rule approximates each small section with a trapezoid and adds their areas. It is especially useful when a function is known only through sampled measurements.

For smooth functions, increasing the number of samples often improves the approximation, but more samples also require more computation. Always consider numerical error and whether the samples represent the underlying phenomenon adequately.

Scientific habit: Before running a program, predict what it will do. Then compare your prediction with the output and explain any difference.

Worked example

Approximate the integral of sin(x) from 0 to π. Its exact value is 2, which gives us a reference for evaluating the error.

example.mMATLAB CODE
x = linspace(0, pi, 101);
y = sin(x);
area_estimate = trapz(x, y);
exact_value = 2;
absolute_error = abs(area_estimate - exact_value);
fprintf('Estimate: %.8f\n', area_estimate);
fprintf('Absolute error: %.3e\n', absolute_error);

trapz uses the spacing in x as well as the sampled y values. Compare 11, 101 and 1001 samples to investigate convergence.

Try it yourself

Think about a sampled integral before running a program.

Quick check

What is the exact value of the integral of sin(x) from 0 to π?

Reveal hint and answer
Hint: An antiderivative is −cos(x). Evaluate it at the two limits.
Answer: 2.

Where this is used

Numerical integration is used for energy calculations, signal power, spectral band areas, accumulated dose and experimental data analysis.

Academy homeNext: Plotting & data analysis