问题描述
我试图通过替换常见的较小表达式来简化大型表达式.这是完整的表达:
I am trying to simplify a large expression by substitution of common smaller expressions.Here is the full expression:
例如,我想做:
exp.subs(L_r*cos(alpha)-L_p*sin(alpha),L_r_tilde))
该表达式可以在 1 中找到两次.我也尝试用相同的方法替换一个较小的表达式,但 SymPy 需要在第一步中进行因式分解来执行替换.
The expression can be found twice in the 1.I also tried to substitute a smaller expression with the same approach, but SymPy requires factorization in the first step to perform the substitution.
这个有效:
small_exp = L_p*sin(alpha)**2-L_r*sin(alpha)*cos(alpha)
small_exp_factorized = small_exp.factor()
small_exp_factorized.subs(L_p*sin(alpha)-L_r*cos(alpha),L_r_tilde)
导致 L_r_tilde*sin(alpha)
但没有事先分解,SymPy 无法替代.
leading to L_r_tilde*sin(alpha)
but without prior factorization SymPy fails to substitute.
是否可以在不分解或进一步操作上述大型表达式的情况下替换所有常用表达式?
Is it possible to substitute all common expressions without factorization or further manipulation of the large expression from above?
推荐答案
SymPy 的 subs
只会替换完全出现在表达式中的内容.它有一些小启发(例如处理 (x**4).subs(x**2, y)
,但没有任何东西可以为您考虑或以其他方式重写表达式.
SymPy's subs
is only going to replace things that appear exactly in an expression. It has a couple of minor heuristics (like handling of (x**4).subs(x**2, y)
, but nothing that will factor or otherwise rewrite expressions for you.
一个技巧是重新排列替换,以便您只替换一个术语,例如
One trick is to rearrange the substitution so that you are only substituting one term, like
small_exp.subs(L_p*sin(alpha), L_r*cos(alpha) + L_r_tilde)
简化后,一切都应该取消.
After simplification, everything should cancel out.
对于您的特定表达式,您的子表达式的每个实例似乎都乘以 sin(alpha)
,因此您可以将该术语包含在您的 L_r_tilde
定义中,或者您可以将 L_r*cos(alpha)*sin(alpha) -L_p*sin(alpha)**2
替换为 L_r_tilde*sin(alpha)
.
For your specific expression, it looks like every instance of your subexpression is multiplied by sin(alpha)
, so you could just include that term in your definition of L_r_tilde
, or you can replace L_r*cos(alpha)*sin(alpha) -L_p*sin(alpha)**2
with L_r_tilde*sin(alpha)
.
我还将指出 cse()
函数,它会自动提取常见的子表达式.
I'll also point out the cse()
function, which pulls out common subexpressions automatically.
这篇关于Sympy替代数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!