I'm trying to calculate the derivative of a function in Python like so:

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

However, I run into the problem of limited float precision. This is
evident for this:
import math
print D5(D5(D5(D5(math.sin))))(0.3)
 => -5551.11512313
print math.sin(0.3)
 => 0.295520206661
Is there any way that any of you can think of to avoid this for
general-purpose functions? Thanks.
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to