SymPy,使用已知模式或子表达式的简化/替换

编程入门 行业动态 更新时间:2024-10-27 17:10:24
本文介绍了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表达式中手动替换了bj和cj以获得:

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)

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

Read docs.sympy/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,使用已知模式或子表达式的简化/替换

本文发布于:2023-06-05 01:22:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/508963.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   模式   SymPy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!