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

Click For Summary
SUMMARY

The discussion centers on the limitations of foolproofing user-defined derivative functions in MATLAB, specifically the function numderivative. The code provided calculates the derivative of a function f(x) at specified points but encounters issues with small tolerances leading to erroneous results. Key insights include the importance of selecting an appropriate step size h and implementing error checks to prevent misleading outputs, particularly when error = 0 indicates a potential problem with the choice of h.

PREREQUISITES
  • Understanding of MATLAB programming and syntax
  • Familiarity with numerical differentiation concepts
  • Knowledge of error analysis in numerical methods
  • Experience with user-defined functions in MATLAB
NEXT STEPS
  • Research MATLAB's built-in functions for numerical differentiation, such as diff and gradient
  • Explore techniques for adaptive step size selection in numerical methods
  • Learn about error handling and validation in MATLAB functions
  • Investigate alternative numerical differentiation methods, such as Richardson extrapolation
USEFUL FOR

Mathematics and engineering students, MATLAB programmers, and developers working on numerical analysis or computational mathematics who need to implement reliable derivative calculations.

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   Reactions: Greg Bernhardt

Similar threads

  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 8 ·
Replies
8
Views
3K
Replies
2
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 9 ·
Replies
9
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 14 ·
Replies
14
Views
4K