1

Is there a good reason to use Derivative instead of diff in the definition (and solution) of an ODE in Sympy? diff seems to do the job just fine:

Solution of a simple ODE

  • 1
    According to the docs, and examples, `diff`, `f(x).diff` and `Derivative` all do the same thing, with possible minor differences in syntax. Look at the `type(diff(f(x),x,2))` – hpaulj Apr 01 '22 at 16:02

2 Answers2

4

diff is a "wrapper" method that it is going to instantiate the Derivative class. So, doing this:

from sympy import *
expr = x**2
expr.diff(x)

# out: 2*x

is equivalent to do:

Derivative(expr, x).doit()

# out: 2*x

However, the Derivative class might be useful to delay the evaluation of a derivative. For example:

Derivative(expr, x)

# out: Derivative(x**2, x)

But the same thing can also be achieved with:

expr.diff(x, evaluate=False)

# out: Derivative(x**2, x)

So, to answer your question, in the example you provided there is absolutely no difference in using diff vs Derivative.

If expr.diff(variable) can be evaluated, it will return an instance of Expr (either a symbol, a number, multiplication, addition, power operation, depending on expr). Otherwise, it will return an object of type Derivative.

Davide_sd
  • 10,578
  • 3
  • 18
  • 30
1

The Derivative object represents an unevaluated derivative. It will never evaluate, for example:

>>> Derivative(x**2, x)
Derivative(x**2, x)

diff is a function which always tries to evaluate the derivative. If the derivative in question cannot be evaluated, it just returns an unevaluated Derivative object.

>>> diff(x**2, x)
2*x

Since undefined functions are always things whose derivatives won't be evaluated, Derivative and diff are the same.

>>> diff(f(x), x)
Derivative(f(x), x)
>>> Derivative(f(x), x)
Derivative(f(x), x)

There's only a difference between the two in cases where the derivative can be evaluated. For ODEs, this means that it generally doesn't matter, except maybe if you have something like the following that you don't want expanded

>>> diff(x*f(x), x)
x*Derivative(f(x), x) + f(x)
>>> Derivative(x*f(x), x)
Derivative(x*f(x), x)
asmeurer
  • 86,894
  • 26
  • 169
  • 240