Search code examples
pythonfunctionreferencederivative

Calculate derivative for provided function, using finite difference, Python


I should probably start by saying that I am relatively new to python, but I have coded in java and Matlab before.

In python, the code

def func(f):
    return f
g = func(cos)
print(g(0))

gives the result

>1.0

as g now is defined as the cosine function.

I want to write a function that calculates the derivative of any provided function using a finite difference approach. The function is defined as

def derivator(f, h = 1e-8):

and would like to achieve the follwing:

g = derivator(cos)
print(g(0)) # should be about 0
print(g(pi/2)) # should be about -1

At the moment my derivator function looks like this

def derivator(f, h = 1e-8):
    return (f(x+h/2)-f(x-h/2))/h

which definitely is wrong, but I am not sure how I should fix it. Any thoughts?


Solution

  • Your current derivator() function (which should probably be called differentiator()) uses an undefined variable x and would return a single value, if x were defined--the value of f'(x). You want to return a function that takes an x value. You can define an inner function and return it:

    def fprime(x):
        return (f(x+h/2)-f(x-h/2))/h
    return fprime
    

    Because you don't use that function anywhere else, though, you can use lambda instead, which is also shorter:

    return lambda x: (f(x+h/2)-f(x-h/2))/h
    

    The only thing PEP 8 says about lambdas is that you should not assign the result of the lambda to a variable, then return it:

    fprime = lambda x: (f(x+h/2)-f(x-h/2))/h  # Don't do this!
    return fprime