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.
No products are associated with this question.
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.
Play games and win prizes!Learn more