Use Matlab or C++ ////////// 1.7 (a) Write a program to compute an ap- proximate
ID: 3747899 • Letter: U
Question
Use Matlab or C++ //////////
1.7 (a) Write a program to compute an ap- proximate value for the derivative of a function using the finite-difference formula f(r h) - f(x) Test your program using the function sin(x) for 1. Determine the error by compar- ing with the built-in function cos(x). Plot the magnitude of the error as a function of h, for You should use a log scale 2 4 8 for h and for the magnitude of the error. Is there a minimum value for the magnitude of the error? How does the corresponding value for h compare with the rule of thumb mac (b) Repeat the exercise using the centered dif- ference approximation f(z h 2hExplanation / Answer
Part (a):
MATLAB CODE
f = @(x) sin(x); % function handler for The function sin(x)
x = 1;% The point at which the function computing the derivative
k = 1:50;% number of h values tested
h = 2.^(-k);
df = (f(x+h) - f(x))./h;% find the derivative
err = abs(df - cos(x));% find the error
loglog(h,err) % plotting the figure in log x and log y graph
grid on % grid on command
xlabel('h');% x axis lable
ylabel('error');% y axis label
for i=1:50
if(err(i) == min(err))
H = h(i); % h corresponding to minimum error
end
end
ApproxH = sqrt(abs(3*(4/3-1)-1))*abs(x); % h approx sqrt(exs mach)
fprintf(' h corresponding to minumum error %e rule of thum h = %e ',H,ApproxH);
Part (b):
f = @(x) sin(x); % function handler for The function sin(x)
x = 1;% The point at which the function computing the derivative
k = 1:50;% number of h values tested
h = 2.^(-k);% creating a vector of h of various values as mentioned in problem
df = (f(x+h) - f(x-h))./(2.*h);% finding the derivative
err = abs(df - cos(x));% finding the error
loglog(h,err) % plotting the figure in log x and log y graph
grid on % grid on command
xlabel('h');% x axis lable
ylabel('error');% y axis label
for i=1:50
if(err(i) == min(err))
H = h(i); % h corresponding to minimum error
end
end
ApproxH = sqrt(abs(3*(4/3-1)-1))*abs(x); % h approx sqrt(exs mach)
fprintf(' h corresponding to minumum error %e rule of thum h = %e ',H,ApproxH);
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.