I use the following function to approximate the derivative of a function at a point:
def prime_x(f, x, h): if not f(x+h) == f(x) and not h == 0.0: return (f(x+h) - f(x)) / h else: raise PrecisionError
As a test, I pass f as fx and x as 3.0. Where fx :
def fx(x): import math return math.exp(x)*math.sin(x)
which has exp(x)*(sin(x)+cos(x)) as a derivative. Now, according to Google and my calculator
exp(3)*(sin(3)+cos(3)) = -17.050059 .
So far so good. But when I decided to test a function with small values ββfor h , I got the following:
print prime_x(fx, 3.0, 10**-5) -17.0502585578 print prime_x(fx, 3.0, 10**-10) -17.0500591423 print prime_x(fx, 3.0, 10**-12) -17.0512493014 print prime_x(fx, 3.0, 10**-13) -17.0352620898 print prime_x(fx, 3.0, 10**-16) __main__.PrecisionError: Mantissa is 16 digits
Why does the error increase when h decreases (after a certain point)? I expected the opposite until f(x+h) was equal to f(x) .
Alex source share