SymPy,使用已知模式或子表达式的简化/替换 [英] SymPy, simplification / substitution using known patterns or sub-expressions

查看:279
本文介绍了SymPy,使用已知模式或子表达式的简化/替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下表达式:

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)

可以简化:

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)

给出子表达式:

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

目前,我在简化的u0表达式中手动替换了bjcj以获得:

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))

是否可以使用SymPy来实现这一目标,而避免手动替换?

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

推荐答案

我想您缺少的是subs将替换任意表达式,而不仅仅是符号

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)

(我使用了simplify,因为这是pi*j*(phi + t)/(2*phi)而不是pi*j/2 + pi*j*t/(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)

阅读 http://docs.sympy.org/0.7.3/tutorial/basic_operations. html#substitution 了解有关替换和替换的更多信息.如果要进行更高级的替换,请查看

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.

这篇关于SymPy,使用已知模式或子表达式的简化/替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆