pank pank - 19 days ago 6
Python Question

Sympy: derivative and subs

I have this code:

from sympy import *
x = Symbol("x")
f = Function("f")(x)
diff(3*x + 2, x) # == 3
diff(f, x).subs(f, 3*x + 2) # == Derivative(3*x + 2, x) <- Why not 3?


Why
sympy
not evaluates the expression when I substituted for
f
the expression with
x
?

Answer

diff(f, x) can't derivate the function yet, so it results in the abstract Derivative(f(x), x). Substitution doesn't do any evaluation, so substituting f for 3*x + 2 results in Derivative(3*x + 2, x). If you want to evaluate it, just append doit():

>>> diff(f, x).subs(f, 3*x + 2).doit()
3
Comments