Help finding a derivative using tolerance and while loop

7 views (last 30 days)
I need to make an m-file myderivative(f,a,tol) where f is a function handle for x, a is a real number and tol is a small positive number. I need the file to approximate f'(a) by finding (f(a+h)-f(a))/h for h=1,1/2,1/3,1/4.... until successive values differ by less than tol using a while loop.
Even though I know this isn't right, I have:
function r=myderivative(f,a,tol)
y=subs(diff(f),x,a);
for n=1:inf;
h=1/n;
while (1/n+1)-h<tol;
(f(a+h)-f(a))/h;
end
end
r=y

Answers (1)

Geoff Hayes
Geoff Hayes on 19 Aug 2014
Renee - start with just the basic outline of your function. You have the signature and you need a while loop. Rather than having one that goes to infinity, set an upper bound on the maximum number of iterations just so that your code doesn't get stuck (this is a good practice to get into when using while loops)
function r=myderivative(f,a,tol)
% initialize the output to something
y = 0;
% only allow 500 iterations
maxIters = 500;
n = 1;
while n<=maxIters
% set h
h = 1/n;
% do the real work here
% increment n
n = n + 1;
end
So now you have a basic loop that doesn't really do anything, but you'll never get stuck in an infinite loop.
Now your code must approximate f'(a) by finding (f(a+h)-f(a))/h for h=1,1/2,1/3,1/4.... until successive values differ by less than tol. So the above code is missing the calculation of f(a+h)-f(a))/h and some sort of comparison. What should that comparison be?

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!