user7088941
user7088941

Reputation: 361

Can't get sympy to reduce a differentiate expression

Consider the following code, which is best viewed in a Jupyter notebook, because of the mathematical output the variables a,b,c below contain:

# cell1
import sympy as sp
from sympy import init_printing
init_printing() 
u, x = sp.symbols('u x')
f = sp.Function('f')

# cell2: building my function
a = f(x)**2
a

# cell3: doing some stuff to the function
b = a.diff(x).subs([(x,u**2)])
b

# cell4: now I have decided what f should be
c = b.replace(f, lambda x: x**2+x,)
c

but I can't get c to actually symbolically evaluate it, so that I get an expression that doesn't contain a derivative. I have tried everything, simplify, cse etc., nothing seems to work.

Of course I could specify a function at the beginning and then I wouldn't have had this problem. But the thing is I want to keep everything up to b and easily switch functions only at that stage as -for mathematical reasons- it is important for me to view how expression b looks like "abstractly", when I don't have already a concrete function in place, and investigate only afterwards see what happens, when I plug in different concrete functions.

Upvotes: 0

Views: 60

Answers (1)

Oscar Benjamin
Oscar Benjamin

Reputation: 14470

You can use the .doit() method to trigger the evaluation of derivatives:

In [25]: c                                                                                                                        
Out[25]: 
  ⎛ 4    2⎞ ⎛d ⎛ 2    ⎞⎞│    
2⋅⎝u  + u ⎠⋅⎜──⎝x  + x⎠⎟│   2
            ⎝dx        ⎠│x=u 

In [26]: c.doit()                                                                                                                 
Out[26]: 
  ⎛   2    ⎞ ⎛ 4    2⎞
2⋅⎝2⋅u  + 1⎠⋅⎝u  + u ⎠

Upvotes: 1

Related Questions