Ask Your Question
0

collect variables buried in an expression

asked 2017-07-27 11:18:33 -0500

Chris Chiasson gravatar image

updated 2017-07-27 17:54:53 -0500

Suppose we have

var('Pmean,alpha,M,Nb,D,H,c');
sol3= [M == 1/4*(2*D*Nb*Pmean - (D*H*alpha + D*H)*c)/((alpha + 1)*c)]

How would you collect the coefficients of D*H in the second term?

Specifically, once the collection is done, how could the factored version of the expression be returned?

I know from using other computer algebra systems that it can be taken all the way to this:

M==1/4*D*(-H+(2*Nb*Pmean)/((1+alpha)*c))
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2017-07-27 11:47:48 -0500

mforets gravatar image

updated 2017-07-28 12:25:17 -0500

what about using coefficient():

sage: expr = sol3[0].rhs()
sage: expr.coefficient(D*H)
-1/4

let me mention that wild cards could also be useful in this type of task:

sage: var('DH'); w0 = SR.wild();
sage: expr.subs({D*H*w0 : DH*w0}).coefficient(DH)
-1/4

Edit: there is the following trick of adding/removing the term of interest which works here:

sage: DHterm = expr.coefficient(D*H)*D*H
sage: ((expr-DHterm).factor() + DHterm).collect(D)
-1/4*D*(H - 2*Nb*Pmean/((alpha + 1)*c))

... but it would be nice to know if there is a more "direct" (=one command) method!

edit flag offensive delete link more

Comments

I gave an upvote because you showed me something new. I am also updating my question to clarify it.

Chris Chiasson gravatar imageChris Chiasson ( 2017-07-27 17:48:40 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2017-07-27 11:18:33 -0500

Seen: 39 times

Last updated: Jul 28