% truncation_example_3.m % Truncation error example #3 % A Riemann sum to approximate a limit of Riemann sums function foo xmin = 0; xmax = 1; fprintf('\nNo. of subintervals Riemann sum\n'); n=1; for k = 1:11 dx = ( xmax - xmin ) / n; s = 0; for i = 0:n-1 x = xmin + ( i + 0.5 ) * dx; s = s + f(x) * dx; end fprintf('%14i %23.15f\n',n,s); n = n * 2; % increase the number of subintervals and repeat end fprintf('\n'); end function fofx = f(x) fofx = x^2; end