Ask Your Question

collect variables buried in an expression

asked 2017-07-27 18:18:33 +0200

Chris Chiasson gravatar image

updated 2017-07-28 00:54:53 +0200

Suppose we have

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:

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2017-07-27 18:47:48 +0200

mforets gravatar image

updated 2017-07-28 19:25:17 +0200

what about using coefficient():

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

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)

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


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-28 00:48:40 +0200 )edit

answered 2017-08-24 08:34:04 +0200

rws gravatar image

It sometimes helps to expand and factor:

sage: s
1/4*(2*D*Nb*Pmean - (D*H*alpha + D*H)*c)/((alpha + 1)*c)
sage: s.expand()
-1/4*D*H*alpha/(alpha + 1) - 1/4*D*H/(alpha + 1) + 1/2*D*Nb*Pmean/((alpha + 1)*c)
sage: _.factor()
-1/4*(H*alpha*c - 2*Nb*Pmean + H*c)*D/((alpha + 1)*c)
sage: _.partial_fraction()
1/4*(2*Nb*Pmean - (H*alpha + H)*c)*D/((alpha + 1)*c)
edit flag offensive delete link more

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


Asked: 2017-07-27 18:18:33 +0200

Seen: 511 times

Last updated: Aug 24 '17