简体   繁体   中英

A function generating the derivative of f

I´m trying to construct a function that return the derivate of f , a function of one variable.

The return value should be a function approximating the derivative of f' using the symmetric difference quotient, so that the returned function will compute (f(x+h) -f(xh))/2h.

The function should start like this:

def derivative(f, x):

which should approximate the derivative of function f around the point x. Does anyone have a clue what type of code I can use to construct this type of function?

/Alex

For a general function f(x), you can straightforwardly obtain a numerical approximation to its first derivative by the standard (second-order) approximation (f(x+h) - f(xh)) /2h. The main challenge is to choose h to be small compared to the lenghscale over which f(x) shows non-quadratic variation, but sufficiently large to avoid round-off errors when subtracting nearby values of f(x).

However, if you want an algebraic method of differentiating your function, then things are more challenging. The easy cases are where f(x) is known to be a polynomial, so can be represented by a vector of coefficients of powers of x. In that case, numpy.polyder() can be used to compute the coefficients of the n'th derivative.

For more complicated functions, you may want to look at SymPy .

Both the numpy.polyder() and SymPy options require you to represent your function in a way that is specialized to these particular tools. I'm not aware of any method that can take an ordinary Python function and construct another function that implements the exact derivative.

what do you want the function to return? If you want the value of the derivative in a certain x, you probably need three arguments:

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

if you want to get a function which calculates the above for any x you can use:

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

Your best best bet would probably be to use SymPy which can do symbolic integration and differentation among other things:

>>> from sympy import *
>>> x, y, z = symbols('x y z')
>>> diff(x**2, x)
2*x

First you can define a function f (Example: f(x) = x ^ 2):

def f(x): return x ** 2

Next using the definition of derivative:

def derivative(function, x, accuracy = 20): # The 'Default' of accuracy is 20 and is an optional argument.
    step = 1 / accuracy
    return (function(x + step) - function(x - step)) / (step * 2)

~~~~~~~~~~~~~~~~~~~~~

By the way, I believe this is a typo:

def derivative(f, h):

Since you are approximating the derivative of function f around the point x , it should be:

def derivative(f, x):

As shown in my code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM