You are on page 1of 2

Engineering Science 204

Numerical Methods in Engineering


First Semester AY 2020-2021

MACHINE EXERCISE No. 6

NAME: REGINA M. LAGATIC STUDENT NO.: 201922598


PROBLEM: Write MATLAB script that computes the first derivative using central difference of
f ( x )=e x at x=0 using different values of h . Plot the error values with respect to h .

INPUT:
Initial value of h .

OUTPUT:
Graph of error vs h .

SOLUTION:

Writing MATLAB script with filename Centraldifference . m

%%Matlab code for log log plot of first derivative


clc
clear

%function for which derivative have to find


f=@(x) exp(x);

%function for exact derivative of the function


df= @(x) exp(x);

%first derivative of the function


fprintf('First derivative of the function \n')
disp(df)

%initial value of h using logspace(a,b,n) to generate logarithmically spaced


points between 10^a and 10^b

hh=logspace(-1,-10,30);

%formula for central derivative


cendiff=@(x,h) (f(x+h)-f(x-h))/(2*h);

%where x0=0
x0=0;
val=df(x0);

fprintf('Exact value for first derivative at x=0 is %f.\n',val);

%loop for error for different h


for i=1:length(hh)
dff(i)=cendiff(x0,hh(i));
error(i)=abs(val-dff(i));
end

%plotting error vs. h


loglog(hh,error,'o','MarkerFaceColor',[0 0.447 0.741])
xlabel('delta x (h)')
ylabel('Error')
grid("on")
title('Comparison of errors vs. h for central difference')

OUTPUT (after running the script)

First derivative of the function


@(x)exp(x)

Exact value for first derivative at x=0 is 1.000000.


 

You might also like