NUMERICAL

You might also like

Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1of 3

%SIN X

%EXACT DIFFERENTIAL
syms x
h = sin(x);
y = diff(h);
a = vpa(subs(y,x,1));

%NUMERICAL DIFFERENTIAL - forward difference 1st order


f = @(x) sin(x);
x = 1;
[dx] = (0.001:0.001:0.1);
b1 = (f(x+dx)-f(x))./dx;
%error
error1 = double(a) - b1;

%NUMERICAL DIFFERENTIAL - central difference 2nd order


b2 = (f(x+dx)-f(x-dx))./(2*dx);
%error
error2 = double(a) - b2;

%NUMERICAL DIFFERENTIAL - central difference 4th order


b3 = (-f(x+(2*dx))+(8*f(x+dx))-(8*f(x-dx))+f(x-(2*dx)))./(12*dx);
%error
error3 = double(a) - b3;

%PLOTS OF LOG ERROR VS DELTA X

%COS X
%EXACT DIFFERENTIAL
syms x
hc = cos(x);
yc = diff(hc);
ac = vpa(subs(yc,x,1));

%NUMERICAL DIFFERENTIAL - forward difference 1st order


fc = @(x) cos(x);
x = 1;
[dx] = (0.001:0.001:0.1);
b1c = (fc(x+dx)-fc(x))./dx;
%error
error1c = double(ac) - b1c;

%NUMERICAL DIFFERENTIAL - central difference 2nd order


b2c = (fc(x+dx)-fc(x-dx))./(2*dx);
%error
error2c = double(ac) - b2c;

%NUMERICAL DIFFERENTIAL - central difference 4th order


b3c = (-fc(x+(2*dx))+(8*fc(x+dx))-(8*fc(x-dx))+fc(x-(2*dx)))./(12*dx);
%error
error3c = double(ac) - b3c;

%PLOTS OF LOG ERROR VS DELTA X

%EXP X
%EXACT DIFFERENTIAL
syms x
he = exp(x);
ye = diff(he);
ae = vpa(subs(ye,x,1));

%NUMERICAL DIFFERENTIAL - forward difference 1st order


fe = @(x) exp(x);
x = 1;
[dx] = (0.001:0.001:0.1);
b1e = (fe(x+dx)-fe(x))./dx;
%error
error1e = double(ae) - b1e;

%NUMERICAL DIFFERENTIAL - central difference 2nd order


b2e = (fe(x+dx)-fe(x-dx))./(2*dx);
%error
error2e = double(ae) - b2e;

%NUMERICAL DIFFERENTIAL - central difference 4th order


b3e = (-fe(x+(2*dx))+(8*fe(x+dx))-(8*fe(x-dx))+fe(x-(2*dx)))./(12*dx);
%error
error3e = double(ae) - b3e;

%PLOTS OF LOG ERROR VS DELTA X FOR SIN X


figure
semilogx(dx, error1, 'black', 'LineWidth', 2);
title('Plot for sin x')
hold on
semilogx(dx, error2, 'red', 'LineWidth', 2);
hold on
semilogx(dx, error3, 'magenta', 'LineWidth', 2);
grid on
legend('1st order accurate forward difference', '2nd order accurate central difference', '4th order
accurate central difference')

%PLOTS OF LOG ERROR VS DELTA X FOR COS X


figure
semilogx(dx, error1c, 'black', 'LineWidth', 2);
title('Plot for cos x')
hold on
semilogx(dx, error2c, 'red', 'LineWidth', 2);
hold on
semilogx(dx, error3c, 'magenta', 'LineWidth', 2);
grid on
legend('1st order accurate forward difference', '2nd order accurate central difference', '4th order
accurate central difference')

%PLOTS OF LOG ERROR VS DELTA X FOR EXP X


figure
semilogx(dx, error1e, 'black', 'LineWidth', 2);
title('Plot for exp x')
hold on
semilogx(dx, error2e, 'red', 'LineWidth', 2);
hold on
semilogx(dx, error3e, 'magenta', 'LineWidth', 2);
grid on
legend('1st order accurate forward difference', '2nd order accurate central difference', '4th order
accurate central difference')

You might also like