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) _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor