# Factor out roots

sage: var('a, b, c, d')
sage: trm = 3*(a+b*sqrt(2))+(1+2*sqrt(2))*(c + d*sqrt(2))
sage: trm.expand()
3*sqrt(2)*b + 2*sqrt(2)*c + sqrt(2)*d + 3*a + c + 4*d


What could I do if I wanted a result like:

(3*b + 2*c + *d)*sqrt(2) + 3*a + c + 4*d


And similar, if there were other roots like sqrt(5), 7^(1/3) etc.

Thank you!

edit retag close merge delete

Sort by ยป oldest newest most voted

The function coefficients may help you, though it is not exactly what you requested for at least three reasons:

sage: e = trm.expand()
sage: e.coefficients(sqrt(2))
[[2*sqrt(2)*c + 3*a + c + 4*d, 0], [3*b + d, 1]]


The three problems:

1. It is not written in the same way as you want, but you can obtain a closer expression like this:

sage: sum([cc[0] * sqrt(2)^cc[1] for cc in c])
sqrt(2)*(3*b + d) + 2*sqrt(2)*c + 3*a + c + 4*d

2. The second, more disturbing problem, is that coefficients seem not to produce what we would like in this case. In particular, we would like to have

sage: e.coefficients(sqrt(2))
[[3*a + c + 4*d, 0], [2*c + 3*b + d, 1]]


I do not now why this is not the case. It may be a bug.

3. Finally, this works for only one square root as such. Maybe some modification can yield the result with several square roots.

more

The closest you can get is with Maxima's ratsimp:

sage: ex = trm.expand()
sage: m = ex._maxima_()
sage: m.ratsimp(sqrt(2)).sage()
sqrt(2)*(3*b + d) + 2*sqrt(2)*c + 3*a + c + 4*d

more

You can "collect" terms for a symbolic variable, so if you temporarily replace sqrt(2) with a symbol, you're good to go:

sage: var('R')
R
sage: trm.expand().subs(sqrt(2)==R).collect(R).subs(R=sqrt(2))
sqrt(2)*(3*b + 2*c + d) + 3*a + c + 4*d

more