You are on page 1of 2

Program - 3

Aim: To implement Numerical Differentiations


Principle: Differentiation of a given function with single variable

Example: Consider a function

First derivative of f(x) is


Evaluating the derivative value at x=1 using the above formula and for every increment in ‘x’
and taking it as true value.
Again evaluate the function value using the numerical difference formulae as shown below.

Next calculate the error obtained in each case as


(i) Error in forward difference = true value – value from forward difference
(ii) Error in backward difference = true value – value from backward difference
(iii) Error in central difference = true value – value from central difference

Program:
% Comparing Numerical Differential equation formula f'(x)
% Consider 'Central difference', 'Backward difference',
'Forward Difference'
% Consider the function f(x)=tan^-1(x)
%calculate f(x)=1

function z=numdiff(x)
clc;
clear all;
a=1;
truVal=1/(1+a.^2);
h=10.^[-1:-1:-10];
%truVal=(1/(1+(a^2)));
%h=1e-4;
%%Forward Difference formula
fwDiff=(atan(a+h)-atan(a))./h;
errFwd=abs(truVal-fwDiff);
disp(['errin fwd diff => ',num2str(errFwd)]);

%%Back Ward Difference formula


bkdDiff=(atan(a)-atan(a-h))./h;
errBkd=abs(truVal-bkdDiff);
disp(['errin bkd diff => ',num2str(errBkd)]);

%%Central Difference formula


ctrDiff=(atan(a+h)-atan(a-h))./(2*h);
errctr=abs(truVal-ctrDiff);
disp(['errin bkd diff => ',num2str(errctr)]);
loglog(h,errctr,'--r',h,errBkd,'-.m',h,errFwd,'*b')
xlabel('Increment in x value (h)')
ylabel('Error in function value')
legend('Central difference','Backward difference','Forward
Difference')

Output:
errin fwd diff => 0.024169 0.0024917 0.00024992 2.4999e-05 2.5e-06 2.5006e-07 2.4133e-
08 3.0387e-09 4.137e-08 4.137e-08
errin bkd diff => 0.025831 0.0025083 0.00025008 2.5001e-05 2.5e-06 2.4998e-07 2.4717e-
08 3.0387e-09 6.9652e-08 4.137e-08
errin bkd diff => 0.00083082 8.3331e-06 8.3333e-08 8.3317e-10 8.8267e-12 4.1133e-11
2.9193e-10 3.0387e-09 1.4141e-08 4.137e-08

Mapping:
Programming in MATLAB needs the conceptual knowledge and logical thinking for obtaining
the solution for a given problem. Hence the program maps with CO-1, PO-1, PO-5, PO-9, and
PO-10, PO-12.

You might also like