简体   繁体   English

Sympy替代数学表达式

[英]Sympy substitute mathematical expression

I am trying to simplify a large expression by substitution of common smaller expressions. 我试图通过替换常见的较小表达式来简化大型表达式。 Here is the full expression: 这是完整的表达: full_expression_image

For instance, I would like to do: 例如,我想做:

exp.subs(L_r*cos(alpha)-L_p*sin(alpha),L_r_tilde))

The expression can be found twice in the 1 . 该表达式可以在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. 我还尝试用相同的方法替换较小的表达式,但是SymPy在第一步中需要分解以执行替换。

This one works: 这个作品:

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)

leading to L_r_tilde*sin(alpha) but without prior factorization SymPy fails to substitute. 导致L_r_tilde*sin(alpha)但没有事先进行因子分解,SymPy无法替代。

Is it possible to substitute all common expressions without factorization or further manipulation of the large expression from above? 是否可以在不分解的情况下替换所有通用表达式,或者是否可以从上方进一步操作大表达式?

SymPy's subs is only going to replace things that appear exactly in an expression. SymPy的subs只会替换表达式中确切显示的内容。 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. 它有一些次要的启发式方法(例如对(x**4).subs(x**2, y) ,但是没有什么可以为您(x**4).subs(x**2, y)或重写表达式。

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. 简化后,所有内容都应取消。

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) . 对于您的特定表达式,看起来您的子表达式的每个实例都乘以sin(alpha) ,因此您可以在L_r_tilde的定义中包括该术语,或者可以替换L_r*cos(alpha)*sin(alpha) -L_p*sin(alpha)**2L_r_tilde*sin(alpha)

I'll also point out the cse() function, which pulls out common subexpressions automatically. 我还将指出cse()函数,该函数会自动提取常见的子表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM