MATLAB Is There a Limit to Foolproofing Code When Using Derivative Functions in MATLAB?

AI Thread Summary
The discussion revolves around a user-defined function in MATLAB designed to compute the numerical derivative of a function f(x) at specific points. The code iteratively refines the derivative calculation by adjusting the step size h and checking the error against a specified tolerance. However, a concern is raised regarding the potential for the derivative to return zero when it should not, particularly if the tolerance is set too small. Suggestions include implementing a check for when the error equals zero, indicating a possible issue with the chosen step size h. The conversation highlights the limitations of foolproofing code and emphasizes the user's responsibility in ensuring proper function usage.
Link-
Messages
99
Reaction score
0
I wrote a user-defined function in MATLAB that is supposed to take the derivative of a function f(x) in the point that correspond to (x,f(x)). Here's the code
Code:
function [fprime]=numderivative(f,x,h,tol)

hd=h*10^-1;
hh=h;
hhdd=hd;
itnum=numel(x);
error=tol+1;
for ii=1:itnum
    while error>tol
        fprime1=(f(x(ii)+h)-f(x(ii)))/h;
        fprime2=(f(x(ii)+hd)-f(x(ii)))/hd;
        error=abs(fprime1-fprime2);
        h=h*10^-1;
        hd=h*10^-1;
    end
    fprime(ii)=fprime1;
    h=hh;
    hd=hhdd;
    error=tol+1;
end
Obviously if you insert a real small tolerance (f(x(ii)+h)-f(x(ii))) would be zero even if the derivative is not zero. I'm trying to come up with something but I just don't know what to do.
Need help.

Thanks
link
 
Physics news on Phys.org
There is a limit to foolproofing code. A user should be responsible for misuse of a function.

In this particular case, a check could be done on the value of error. If error = 0, it could be due to a bad choice of h.
 
  • Like
Likes Greg Bernhardt
Back
Top