rhombidodecahedron
rhombidodecahedron

Reputation: 7922

Merge derivative terms with sympy?

I have a derivative of a product of many variables:

d/dx [f(x) * g(x) * h(x)]

but when I represent this in sympy, it automatically performs the chain rule:

x = Symbol('x')
diff(Function('f')(x)*Function('g')(x)*Function('h')(x), x)

yields

𝑓(𝑥)𝑔(𝑥)𝑑/𝑑𝑥ℎ(𝑥)+𝑓(𝑥)ℎ(𝑥)𝑑/𝑑𝑥𝑔(𝑥)+𝑔(𝑥)ℎ(𝑥)𝑑/𝑑𝑥𝑓(𝑥)

Is there any way in sympy to "undo" this and merge them into the compact notation? (I want to do this for the result of my calculation. I was hoping "simplify" would do it, but it does not.)

Upvotes: 1

Views: 124

Answers (1)

Oscar Benjamin
Oscar Benjamin

Reputation: 14470

You can use Derivative rather than diff:

In [4]: diff(f(x)*g(x), x)                                                                                                                                    
Out[4]: 
     d               d       
f(x)⋅──(g(x)) + g(x)⋅──(f(x))
     dx              dx      

In [5]: Derivative(f(x)*g(x), x)                                                                                                                              
Out[5]: 
d            
──(f(x)⋅g(x))
dx 

I'm not aware of a simplification routine that will "invert" the product rule but if you know the product you are expecting then you can use a substitution for it:

In [25]: e = diff(f(x)*g(x), x)                                                                                                                               

In [26]: e                                                                                                                                                    
Out[26]: 
     d               d       
f(x)⋅──(g(x)) + g(x)⋅──(f(x))
     dx              dx      

In [27]: e.subs(g(x), h(x)/f(x)).doit().factor().subs(h(x), f(x)*g(x))                                                                                        
Out[27]: 
d            
──(f(x)⋅g(x))
dx 

Upvotes: 1

Related Questions