import math def deriv2(f,x,h): return (f(x+h)-f(x-h))/2/h def deriv(f,x): h=max(math.fabs(x),math.fabs(f(x)))/2**15 if h==0: h=1e-30 h=((x+h)-(x-h))/2 d1=deriv2(f,x,h) h=h/2 h=((x+h)-(x-h))/2 d2=deriv2(f,x,h) return (4*d2-d1)/3 x=.7 print deriv(math.cos,x), deriv(math.cos,x)+math.sin(x)