Calculate derivative for provided function, using finite difference, Python -
i should start saying relatively new python, have coded in java , matlab before.
in python, code
def func(f): return f g = func(cos) print(g(0))
gives result
>1.0
as g
defined cosine function.
i want write function calculates derivative of provided function using finite difference approach. function defined as
def derivator(f, h = 1e-8):
and achieve follwing:
g = derivator(cos) print(g(0)) # should 0 print(g(pi/2)) # should -1
at moment derivator function looks this
def derivator(f, h = 1e-8): return (f(x+h/2)-f(x-h/2))/h
which wrong, not sure how should fix it. thoughts?
your current derivator()
function (which should called differentiator()
) uses undefined variable x
, return single value, if x
defined--the value of f'(x)
. want return function takes x value. can define inner function , return it:
def fprime(x): return (f(x+h/2)-f(x-h/2))/h return fprime
because don't use function anywhere else, though, can use lambda
instead, shorter:
return lambda x: (f(x+h/2)-f(x-h/2))/h
the thing pep 8 says lambdas should not assign result of lambda variable, return it:
fprime = lambda x: (f(x+h/2)-f(x-h/2))/h # don't this! return fprime