Derivation

Derivation

Solution 

f.m 

function y=f(x)

y=exp(-x)*sin(pi*x);

end 

soln.m 

dx=0.001; %you can change this value

x=0.4;

%first derivative

%backward difference

df_dxb1=(f(x)-f(x-dx))/dx;

df_dxb2=(3*f(x)-4*f(x-dx)+f(x+dx))/(2*dx);

%forward difference

df_dxf1=(f(x+dx)-f(x))/dx;

df_dxf2=(-3*f(x)+4*f(x+dx)-f(x-dx))/(2*dx);

%central difference

df_dxc=(f(x+dx)-f(x-dx))/(2*dx);

%second derivative

d2f_dx2=(f(x-dx)-2*f(x)+f(x+dx))/(dx^2);

%exact value of dy/dx

syms g(z)

g(z)=exp(-z)*sin(pi*z);

df=diff(g,z);

dy_dx=double(df(0.4));

%exact value of d2y/dx2

df2=diff(diff(g,z));

d2y_dx2=double(df2(0.4));

%for first order first derivative

dx=10^-6;

i=1;

while dx<=1

Ef(i)=abs(dy_dx-((f(x+dx)-f(x))/dx));

Eb(i)=abs(dy_dx-((f(x)-f(x-dx))/dx));

Ec(i)=abs(dy_dx-((f(x+dx)-f(x-dx))/(2*dx)));

dx=dx*10;

i=i+1;

end

dx=[10^-6, 10^-5, 10^-4, 10^-3, 10^-2, 10^-1, 10^0];

plot(dx,Ef);

grid on;

hold on;

title(‘Error in First derivative first order’);

xlabel(‘dx’);

ylabel(‘Error’);

plot(dx,Eb);

plot(dx,Ec);

legend(‘forward difference’, ‘backward difference’, ‘central difference’);

fprintf(‘As dx increases error tends to increase and it is minimum for central difference\n’);

%for first derivative second order

i=1;

for j=1:1:length(dx)

Ef2(i)=abs(dy_dx-((-3*f(x)+4*f(x+dx(j))-f(x-dx(j)))/(2*dx(j))));

Eb2(i)=abs(dy_dx-((3*f(x)-4*f(x-dx(j))+f(x+dx(j)))/(2*dx(j))));

Ec2(i)=abs(dy_dx-((f(x+dx(j))-f(x-dx(j)))/(2*dx(j))));

dx=dx*10;

i=i+1;

end

figure();

plot(dx,Ef2);

grid on;

hold on;

title(‘Error in First derivative second order’);

xlabel(‘dx’);

ylabel(‘Error’);

plot(dx,Eb2);

plot(dx,Ec2);

legend(‘forward difference’, ‘backward difference’, ‘central difference’);

fprintf(‘As dx increases error tends to increase and it is minimum for central difference\n’);

i=1;

for j=1:1:length(dx)

Ed(i)=abs(d2y_dx2-((f(x-dx(j))-2*f(x)+f(x+dx(j)))/(dx(j)^2)));

i=i+1;

end

figure();

plot(dx,Ed);

grid on;

title(‘Error in Second derivative’);

xlabel(‘dx’);

ylabel(‘Value of second derivative’);

fprintf(‘As dx increases error tends to increase’);