%-- %-- matlab script to reproduce table 1.1, textbook %-- %-- Finite Difference Methods for Ordinary and Partial %-- Differential Equations by Randall J. LeVeque %-- %-- By Nasser M. Abbasi oct 5, 2010 %-- Math 228A, UC DAVIS, Fall 2010 h=[0.1 0.05 0.01 0.005 0.001]; exact_value = cos(1); result= zeros(4,1); derivative_left = @(h) (sin(1) - sin(1-h))/h; derivative_right = @(h) (sin(1+h) - sin(1))/h; derivative_center = @(h) (sin(1+h) - sin(1-h))/(2*h); derivative_3rd_order = @(h) (2*sin(1+h)+3*sin(1)-6*sin(1-h) ... +sin(1-2*h))/(6*h); fprintf(strcat('%s\t',repmat('%s\t\t',1,4),'\n'),... ' h','D+','D_','D0','D3'); for i=1:length(h) result(1) = derivative_right(h(i)) - exact_value; result(2) = derivative_left(h(i)) - exact_value; result(3) = derivative_center(h(i)) - exact_value; result(4) = derivative_3rd_order(h(i)) - exact_value; fprintf(strcat('%3.1E\t',repmat('%6.4E\t',1,4),'\n'),h(i),result); end