Matlab derivative approximation - can anyone help?

18 views (last 30 days)
I've been puzzling over this last problem in my assignments for the past week or so, and still with no end in sight. Some of the folks here on MathWorks have given me a few pointers, but I still can't make this code work.
function r=myderivative(f,a,tol)
y = 0;
maxIters = 500;
n = 1;
while n<=maxIters
h = 1/n;
while (1/n+1)-h<tol;
y = (f(a+h)-f(a))/h;
end
n = n + 1;
y = (f(a+h)-f(a))/h;
end
r=y;
end
The problem in question instructed me to make an m-file mimicking a derivative function, which would apply (f(a+h)−f(a))/h to f(a) again and again (with h turning into 1, then 1/2, then 1/3...) until the successive values dipped under the "tol" value.
However, this current code skips over pretty much all the stuff after "y=0" and spits out 0 as the value for every set of (f,a,tol).
Could anyone spare a bit of help? I would greatly appreciate it.
  1 Comment
dpb
dpb on 22 Aug 2014
Well, work thru the results of what you've written...for example, look at the following that displays the condition you've calculated for the comparison to tol in the second loop.
>> maxIters=3;
>> n=1;
>> while n<=maxIters
h = 1/n;
(1/n+1)-h
n = n + 1;
end
I just took out the computations and looked at the looping construct. You don't give a value for tol but note that your comparison value never changes as you've got it defined.

Sign in to comment.

Answers (1)

Star Strider
Star Strider on 22 Aug 2014
You need to track the successive values for the derivative y and compare them with the current estimate. The derivative calculation has to go before the second while block, and the second while block has to compare the previous value of the derivative with the current value. As long as that difference is >=tol, replace the previous value of the derivative with the current value and continue.
  16 Comments
Chong
Chong on 23 Aug 2014
Alright, after many hours, much brainstorming, and the sacrifice of a hobo, I finally got the code to work it the way I want. Preserved here for posterity:
function r = myderivative(f,a,tol)
h = 1;
oldapprox = (f(a+h)-f(a))/h;
h = h*(1/h)*(1/(1/h+1));
approx = (f(a+h)-f(a))/h;
while (abs(approx-oldapprox)>tol)
oldapprox = approx;
h=h*(1/h)*(1/(1/h+1));
approx = (f(a+h)-f(a))/h;
end
r = approx;
end
(The real trick is figuring out how to get from 1/n to 1/(n+1) without introducing another bloody variable.)
Star Strider
Star Strider on 23 Aug 2014
Edited: Star Strider on 23 Aug 2014
My original code (from a week or so ago):
tol = 1E-12;
dfdx = @(f,a,h) (f(a+h)-f(a))./h;
dd = Inf;
dprv = 0;
k1 = 1;
while dd > tol
h = 1/k1;
df = dfdx(f,a,h);
dd = df-dprv;
dprv = df;
k1 = k1+1;
end
df % Result
produces:
df =
707.1039e-003

Sign in to comment.

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!