Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(15 points) Write a Matlab funtion called \"mynumdiff.m\" that approximates the

ID: 2265789 • Letter: #

Question

(15 points) Write a Matlab funtion called "mynumdiff.m" that approximates the derivative of an arbitrary function at a given point numerically using the forward finite difference approximation (2). The function definition should be as follows: function fprime - mynumdiff (fn, x0 , tol) % Inputs : %fn - a string, giving the functional form of f(a) x0 - the value of at which f"(x) is to be computed %tol - the tolerance for convergence % Output: fprime - the finite difference approximation to f,(“0) The criterion for convergence is as follows Ar should be initialized to 1, and thern decreased by a factor of 10 until S tol. At that point, fprime should be set equal to D(o,Ax)

Explanation / Answer

%=======MAIN PROGRAM======%

%----Let us take any function in terms of x (You can take any fucntion in terms of 'x' as your own wish====%
fn=@(x) x^3+x^2+x;
%-----Let us take x0=2------%
x0=2;
%-----tol=0.0001, As the tolerance is reduced we will get better approximation for the differentiation value------%
tol=0.0001;
fprime=mynumdiff(fn,x0,tol);
display(['The finite difference approximation of the function fn at x=x0 is ',num2str(fprime)]);

%======Function File "mynumdiff.m"======%

function fprime=mynumdiff(fn,x0,tol)
temp_tol=1;
delta_x=1;
diff1=0;
while temp_tol>tol
delta_x1=delta_x;
delta_x2=delta_x/10;
diff1=(fn(x0+delta_x1)-fn(x0))/delta_x1;
diff2=(fn(x0+delta_x2)-fn(x0))/delta_x2;
delta_x=delta_x/10;
temp_tol=abs((diff2-diff1)/diff1);
end
fprime=diff1;

%======END======%

Output:

The finite difference approximation of the function fn at x=x0 is 17.0007

Here the Actual value of f'(x0)=17. As we reduce the tolerance, we will get better approximation.