Search code examples
pythonsympyderivative

nth derivative with sympy


I'm a bit new to sympy
I would like to compute nth derivative of an expression using sympy; however, I don't understand how the diff function works for nth derivative:

from sympy import diff, symbols

x = symbols("x")
f = ((x**2-1)**5)

# for n = 2
# from the sympy docs, I do:
d_doc = diff(f, x, x)

# using the diff two times
d_2 = diff(diff(f, x), x)

I get two different results:

>>> d_doc
10*(x**2 - 1)**3*(9*x**2 - 1)

>>> d_2
80*x**2*(x**2 - 1)**3 + 10*(x**2 - 1)**4

d_2 is the correct answer in this case.

Why is this?
is there a way to make a function that takes a n and returns the nth derivative?


Solution

  • The answer in an easy place, (from Pranav Hosangadi's comment):

    It is the same, diff(f, x, x) simplifies the expression

    >>> simplify(diff(f,x,x))
    (x**2 - 1)**3*(90*x**2 - 10)
    >>> simplify(diff(diff(f,x),x))
    (x**2 - 1)**3*(90*x**2 - 10)