Section 8.1 Riemann sums
The Fundamental Theorem of Calculus tells us that
∫baf(x)dx=F(b)−F(a)
for any antiderivative F(x) of f(x). Unfortunately, though, very few functions have an antiderivative that can be written in terms of elementary functions. For instance, f(x)=e−x2 does not! The idea of numerical integration is to devise algorithms able to evaluate directly the integral as the area under the graph.
A simple example: Riemann sums. Every student already met such a method in Calculus 1: Riemann sums! For every continuous function (and many others), the Riemann integral can be defined as the limit of the left Riemann sum:
∫baf(x)dx=limn→∞[f(a)+f(a+h)+⋯+f(a+(n−1)h)]h,
where h=(b−a)/n.

Ln=[f(a)+f(a+h)+⋯+f(a+(n−1)h)]h.
Below is a simple MATLAB implementation of this algorithm, used to evaluate the integral of sinx from 0 to 2. xxxxxxxxxx
format long
a=0; b=2; h=0.01;
x=a:h:b;
x(end)=[]; %let's get rid of b
L = sum(h*sin(x)) % Riemann sum
I = 1-cos(2) % Exact value of the integral
|∫baf(x)dx−Ln|≤b−a2hmax[a,b]|f′(x)|.
Convergence Speed. The formula above shows that the truncation error of the Riemann sum is O(h1). Below we visualize this scaling law by evaluating the error in the computation of ∫20sin(x)dx. In this case, due to the slow convergence of this method, it is not possible to set h smaller than 10−8 since otherwise the number of summands becomes too large to handle for either MATLAB or Octave. The minimum error achievable with this method for this integral is hence of the order of 10−8. Notice also that, in this range for h, the round-off component of the error is not visible. xxxxxxxxxx
format long
n=8;
a=0; b=2; h(1)=0.1;
s = zeros(n); err = zeros(n);
for i = 1:n
x=a:h(i):b; % these are the x_i
x(end)=[]; %let's get rid of b
s(i)=sum(h(i)*sin(x)); % this is the integral
err(i)=abs(1-cos(2)-s(i)); % and this is the actual error
h(i+1) = h(i)/10;
end
x=2:n;
clf
[h(x)' err(x)']
loglog(h(x),err(x));
hold on
loglog(h(x),h(x));
xlabel('h')
ylabel('y')
legend({'y=error(h)','y=h'},'Location','northwest')