% integ_test calculates a numerical approximation to the integral % of a function and plots the error as a function of Delta x. % Programmer: Dick Furnstahl furnstahl.1@osu.edu % % Revision history: % 10-Apr-2005 -- original version for Physics 263 % % To do: % * Calculate the "exact" answer using MATLAB's built-in functions % % clear the memory clear; % set the limits of the integral and put in the exact result % (which depends on the test integrand, of course!) a = 0; b = 1; test_integral1_exact = exp(b) - exp(a); % parameters defining the range of the calculation N_min = 10; % starting number of integration subintervals N_max = 200; % final number of integration subintervals Delta_N = 5; % increment in number of intervals % Now we step through each value of N (e.g., N=10 then 15 then 20 up % to N_max) using a "loop". The loop extends from the % "for" statement until the "end" (i.e., the indented part). counter = 0; % start a counter at 0 for N = N_min : Delta_N : N_max counter = counter + 1; % increment the counter % set the current element of Delta_x Delta_x(counter) = (b-a) / N; % figure out Delta x from the total % number of subintervals % evaluate an approximation to the test integral integral_naive = integ_naive('test_integrand1', a, b, N); % evaluate the <> error by comparing to the exact result % (note the use of the absolute value function "abs" so % error > 0 always) % (... means continued to the next line) error_naive(counter) = abs( (integral_naive - test_integral1_exact) ... / test_integral1_exact ); end % plot the error vs. Delta_x on a log-log plot % To plot two curves, use loglog(Delta_x,error1,Delta_x,error2) loglog(Delta_x,error_naive) xlabel('Delta x'); ylabel('|relative error|'); % add labels for axes