[Tutor] Functional Derivatives

Chris Fuller cfuller084 at thinkingplanet.net
Tue Apr 21 07:38:58 CEST 2009


His problem was composing four functions, each with a small error.  The first 
two applications work well enough, but there is a about a percent error in 
the third composition.  The big source of error is f(x+h)-f(x).  Subtracting 
two floating point numbers that are nearly equal is a known source of 
innaccuracy.  Scaling all the terms by a very large number reduced the error, 
but not as well as fewer compositions.

Cheers

BIGNUM = 1

def D5(func, h=1e-5):
    ""' Return derivative of function func'''
    def df(x):
        return (BIGNUM*func(x+h)-BIGNUM*func(x))/(BIGNUM*h)
    return df

import math

print D5(math.sin)(0.3)
print math.cos(0.3)

print D5(D5(math.sin))(0.3)
print -math.sin(0.3)

print
print D5(D5(D5(math.sin)))(0.3)
print -math.cos(0.3)

# actually, other powers, higher or lower, work less well..
BIGNUM = 1e10
print D5(D5(D5(math.sin)))(0.3)
print -math.cos(0.3)


More information about the Tutor mailing list