SymPy, simplification / substitution using known patterns or sub-expressions

与世无争的帅哥 提交于 2020-01-03 08:43:07

问题


I have the following expression:

from sympy import pi, sin, cos, var, simplify
var('j,u,v,w,vt,wt,a2,t,phi')

u0 = v*a2*sin(pi*j/2 + pi*j*t*phi**(-1)/2) + pi*vt*a2*cos(pi*j/2 + pi*j*t*phi**(-1)/2)*j*phi**(-1)/2 + pi*w*a2*cos(pi*j/2 + pi*j*t*phi**(-1)/2)*j*phi**(-1)

Which can be simplified:

print simplify(u0)
#a2*(pi*j*vt*cos(pi*j*(phi + t)/(2*phi)) + 2*pi*j*w*cos(pi*j*(phi + t)/(2*phi)) + 2*phi*v*sin(pi*j*(phi + t)/(2*phi)))/(2*phi)

Given the sub-expressions:

bj = pi*j*(phi + t)/(2*phi)
cj = j*pi/(2*phi)

Currently I substitute manually bj and cj in the simplified u0 expression to get:

u0 = a2*(v*sin(bj) + cj*vt*cos(bj) + 2*cj*w*cos(bj))

Is it possible to use SymPy to achieve that, avoiding the manual substitution?


回答1:


I guess what you are missing is that subs will replace arbitrary expressions, not just symbols

>>> print simplify(u0).subs({pi*j*(phi + t)/(2*phi): bj, j*pi/(2*phi): cj})
a2*(pi*j*vt*cos(bj) + 2*pi*j*w*cos(bj) + 2*phi*v*sin(bj))/(2*phi)

(I used simplify because that is what results in the pi*j*(phi + t)/(2*phi) instead of pi*j/2 + pi*j*t/(2*phi), but it's not otherwise required)

Read http://docs.sympy.org/0.7.3/tutorial/basic_operations.html#substitution for more information about substitution and replacement. If you want to do more advanced replacement, take a look at the replace method.




回答2:


You can find common subexpressions with the cse routine.



来源:https://stackoverflow.com/questions/18011162/sympy-simplification-substitution-using-known-patterns-or-sub-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!