Ask Your Question
0

collect variables buried in an expression

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

Chris Chiasson gravatar image

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

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

2 Answers

Sort by ยป oldest newest most voted
2

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

mforets gravatar image

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

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

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

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

Stats

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

Seen: 657 times

Last updated: Aug 24 '17