Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

python - 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. I also tried to substitute a smaller expression with the same approach, but SymPy requires factorization in the first step to perform the substitution.

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.

Is it possible to substitute all common expressions without factorization or further manipulation of the large expression from above?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

I'll also point out the cse() function, which pulls out common subexpressions automatically.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...