function compEM % compEM Compare Euler and Midpoint for solution of dy/dt = -y; y(0) = 1 % % Synopsis: compEM % % Input: none % % Output: times and global trunc errors for a sequence of stepsizes tn = 1; y0 = 1; % Length of interval and initial condition fprintf('\n h Time E errE Time M errM\n'); sizes= 2.^-[1:12]; j=1; for h = sizes %for h = [0.2 0.1 0.05 0.025 0.0125 0.00625] tic; [te,ye] = odeEuler('rhs2',tn,h,y0); timee = toc; % Euler tic; [tm,ym] = odeMidpt('rhs2',tn,h,y0); timem = toc; % Midpoint % --- global discretization errors yex = y0*exp(-te); % Exact solution at discrete t erre = max(abs(ye-yex)); errm = max(abs(ym-yex)); fprintf('%8.5f %7d %11.2e %7d %11.2e\n',h,timee,erre,timem,errm); times(j,1)=timee; times(j,2)=timem; errors(j,1)=erre; errors(j,2)=errm; j=j+1; end loglog(sizes, times(:,1), sizes, times(:,2));legend('time e','time m'); figure; loglog(sizes, errors(:,1), sizes, errors(:,2));legend('error e','error m'); whos