VECH
VECH

Reputation: 103

How to substitute in expression and compute it? Sympy

I have a symbolic function on Sympy, and I have a long expression involving it. For example:

from sympy.abc import x
from sympy import Function
F = Function('F')(x) 
exp = diff(F,x,x).subs(F, x**3+x) + F**2

Now I would like to substitute a particular expression for the function F, and have it evaluate it, for example:

exp.subs(F,x*4)
>>>x**8 + Derivative(x**4, (x, 2))

However, I would like it to return x**8+12*x**2 since this is what you get when you differentiate twice x**4. How can I do this?

Thanks, Eduardo

Upvotes: 0

Views: 75

Answers (1)

smichr
smichr

Reputation: 19029

When there are actions that need to be done after a substitution, you just need to "doit":

>>> F = Function('F')(x)
>>> exp = diff(F,x,x).subs(F, x**3+x) + F**2
>>> exp.subs(F,x*4)
16*x**2 + Derivative(x**3 + x, (x, 2))
>>> _.doit()
16*x**2 + 6*x

(If it can be done it will be done; but sometimes -- like with Integrals -- they will remain undone because there is no solution programmed into SymPy.)

Upvotes: 2

Related Questions