Create a MATLAB script to find the first and second derivati
Solution
function []=forward_First(x,h)
y0=x*exp(x)+3*x^2+2*x-1;
y1=(x+h)*exp(x+h)+3*(x+h)^2+2*(x+h)-1;
y_forward=(y1-y0)/h;
y0=x*exp(x)+3*x^2+2*x-1;
y1=(x-h)*exp(x-h)+3*(x-h)^2+2*(x-h)-1;
y_backward=(y0-y1)/h;
y0=(x+h)*exp(x+h)+3*(x+h)^2+2*(x+h)-1;
y1=(x-h)*exp(x-h)+3*(x-h)^2+2*(x-h)-1;
y_central=(y0-y1)/(2*h);
fprintf(\'\ Derivate of function f at 3 with h= %0.4f is \ \ \\t using Forward Difference Expansion : %0.4f \ \ \\t using BackwardDifference Expansion : %0.4f \ \ \\t using Central Difference Expansion : %0.4f\ \',h,y_forward,y_backward,y_central);
end
OUTPUT:
Derivate of function f at 3 with h= 0.1000 is
using Forward Difference Expansion : 105.8704
using BackwardDifference Expansion : 95.2159
using Central Difference Expansion : 100.5431
----
forward_First(3,0.01)
Derivate of function f at 3 with h= 0.0100 is
using Forward Difference Expansion : 100.8763
using BackwardDifference Expansion : 99.8120
using Central Difference Expansion : 100.3442
----
Derivate of function f at 3 with h= 0.0010 is
using Forward Difference Expansion : 100.3954
using BackwardDifference Expansion : 100.2890
using Central Difference Expansion : 100.3422
-----------------Second derivative------
function []=forward_second(x,h)
y0=x*exp(x)+3*x^2+2*x-1;
y1=(x+h)*exp(x+h)+3*(x+h)^2+2*(x+h)-1;
y2=(x+2*h)*exp(x+2*h)+3*(x+2*h)^2+2*(x+2*h)-1;
y_forward=(y2-2*y1+y0)/h^2;
y0=x*exp(x)+3*x^2+2*x-1;
y1=(x-h)*exp(x-h)+3*(x-h)^2+2*(x-h)-1;
y1=(x-2*h)*exp(x-2*h)+3*(x-2*h)^2+2*(x-2*h)-1;
y_backward=(y0-2*y1+y2)/h^2;
y2=(x+h)*exp(x+h)+3*(x+h)^2+2*(x+h)-1;
y1=(x-h)*exp(x-h)+3*(x-h)^2+2*(x-h)-1;
y0=x*exp(x)+3*x^2+2*x-1;
y_central=(y2-2*y0+y1)/(h^2);
fprintf(\'\ Derivate of function f at 3 with h= %0.4f is \ \ \\t using Forward Difference Expansion : %0.4f \ \ \\t using BackwardDifference Expansion : %0.4f \ \ \\t using Central Difference Expansion : %0.4f\ \',h,y_forward,y_backward,y_central);
end
OUTPUT:
>> forward_second(3,0.001)
Derivate of function f at 3 with h= 0.0010 is
using Forward Difference Expansion : 106.5483
using BackwardDifference Expansion : 601840.5127
using Central Difference Expansion : 106.4277
(b)
First derivative
>> forward_second(1,0.001)
Derivate of function f at 3 with h= 0.0010 is
using Forward Difference Expansion : 14.1657
using BackwardDifference Expansion : 80591.1157
using Central Difference Expansion : 14.1548
>>
Second derivative
>> forward_second(1,0.001)
Derivate of function f at 3 with h= 0.0010 is
using Forward Difference Expansion : 14.1657
using Central Difference Expansion : 14.1548
>>


