Derivative() or diff() in SymPy ODE?

2.1k Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

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)