[英]SymPy, simplification / substitution using known patterns or sub-expressions
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
表达式中手动替换bj
和cj
来获得:
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? 是否可以使用SymPy来实现这一点,避免手动替换?
I guess what you are missing is that subs
will replace arbitrary expressions, not just symbols 我想你缺少的是
subs
会替换任意表达式,而不仅仅是符号
>>> 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) (我使用
simplify
因为这是导致pi*j*(phi + t)/(2*phi)
而不是pi*j/2 + pi*j*t/(2*phi)
,但是否则需要)
Read http://docs.sympy.org/0.7.3/tutorial/basic_operations.html#substitution for more information about substitution and replacement. 有关替换和替换的更多信息,请阅读http://docs.sympy.org/0.7.3/tutorial/basic_operations.html#substitution 。 If you want to do more advanced replacement, take a look at the
replace
method. 如果要进行更高级的替换,请查看
replace
方法。
您可以使用cse
例程找到常见的子表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.