user162343
user162343

Reputation: 209

Estimate the derivative doing the limit in MATLAB

I want write a script in MATLAB that computes the quotient of the derivative (f(x+h)-f(x))/h for the function x^2 at x=2 and h starting at 1 and decreasing by a factor of 10, and the book said that the effect of the rounding error becomes apparent when h gets to small (less than 10^-12).

Then I wrote the following code:

for i=0:-2:-16
    h=10^i;
    ((2+h)^2-(2)^2)./h
end 

Then my question is, How can I improve my code? because It gives me indeed an error saying that the last approximation to the derivative is zero.

Thanks a lot in advance :)

Upvotes: 0

Views: 53

Answers (1)

gregswiss
gregswiss

Reputation: 1456

Due to the limit of floating point arithmetic you are limited in how small you can choose h. An reasonable option for choosing a "safe" small h is using h=x*sqrt(eps) where eps is the distance from 1.0 to the next largest double-precision number, that is, eps = 2^-52

This Wikipedia page contains some more information

If you REALLY wanted higher precision arithmetic you could consider using an implementation of multi-precision arithmetic. For example this is a MATLAB wrapper around the well-established GMP (GNU Multiple Precision Arithmetic Library) and MPFR (multiple-precision floating-point computations with exact rounding)

Upvotes: 1

Related Questions