0

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?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Owen
  • 56
  • 1
  • 8
  • Does this answer your question? [How to find the nth derivative given the first derivative with SymPy?](https://stackoverflow.com/questions/40324336/how-to-find-the-nth-derivative-given-the-first-derivative-with-sympy) – blackbrandt Aug 02 '21 at 14:56
  • 1
    Simplify them. They're both the same. `d_doc.simplify()` gives: `(x**2 - 1)**3*(90*x**2 - 10)`. So does `d_2.simplify()` – Pranav Hosangadi Aug 02 '21 at 15:04
  • 1
    As for _"Is there a way to make a function that takes a n and returns the nth derivative?"_ `diff(f, x, n)` is the same as writing `x, x, x, ..., x` n times. – Pranav Hosangadi Aug 02 '21 at 15:05

1 Answers1

1

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)
Owen
  • 56
  • 1
  • 8
  • 1
    For additional information, one can use `diff(f,x,n)` in order to directly get n-th derivative. For example, `diff(f,x,5)` would be equivalent to `diff(f,x,x,x,x,x)`. – Suneesh Jacob Aug 16 '21 at 18:36