Search code examples
pythonsympyderivative

How to get a numeric derivative function in python?


I wonder to know how to get a derivative function in Python to compose a Taylor series. I know various methods to get a derivative. Symbolic using SymPy library in the following way:

x = sy.Symbol('x')
y = 3*x**2 + 4*x**3
y.diff(x)

As a result I get a new function, but I cannot do anything with this function.

The second way is to differentiate using scipy library in the following way:

def f(x):
    return 3*x**2 + 4*x**3
sc.derivative(f, 2)

But it calculates the derivative in some certain point.

But need to get just some another function f' which is the derivative of f.

Does anybody know to resolve it?

Many thanks.


Solution

  • Just assign the derivative to a variable and use that variable where you want to use the derivative. Take the Newton-Raphson form of an equation: f(x) = f(x0) + (x - x0)/f'(x0). we need an f(x). Let's call it fx:

    >>> fx = 3*x**2 + 4*x**3
    

    We need the derivative. Call it f1x:

    >>> f1x = fx.diff(x)
    

    Assuming f(x) = 0 we calculate x from x0 as x = x0 - f(x0)/f'(x0). We will call x xnew and x0 as x:

    >>> xnew = x - fx/f1x; xnew
    x - (4*x**3 + 3*x**2)/(12*x**2 + 6*x)
    

    To calculate xnew from x = 1 you use substition (when working with integers) or evaluation with substitution to better preserve accuracy when working with Floats)

    >>> xnew.subs(x, 1)
    >>> xnew.subs(x,1)
    11/18
    >>> xnew.n(subs={x:1})
    0.611111111111111
    

    If it makes you feel better to work with the f(x) form you can do the same thing as follows (and here I will just show the steps):

    >>> f = Lambda(x, 3*x**2 + 4*x**3)
    >>> f1 = Lambda(x, f(x).diff(x))
    >>> xnew = x - f(x)/f1(x); xnew
    x - (4*x**3 + 3*x**2)/(12*x**2 + 6*x)
    >>> xnew.subs(x, 1)
    11/18
    

    In either case, be careful to not use x as a Python variable for anything other than the SymPy Symbol x. If you do you will lose (temporarily and perhaps mysteriously, if you are new to Python/SymPy) your ability to recreate f(x) with an x:

    >>> f(x)
    4*x**3 + 3*x**2
    >>> x = 2
    >>> f(x)  # now interpreted as f(2)
    44
    

    Oops! Let's get x pointing to a Symbol again

    >>>> from sympy.abc import x
    >>> f(x)
    4*x**3 + 3*x**2
    

    Note: if you want several derivatives to work with at once you can store them in a list and access them by order of derivative:

    >>> deriv = [f(x).diff(x, i) for i in range(4)]
    >>> deriv[2]
    6*(4*x + 1)