How to recursively factor a symbolic expression?

asked 2017-06-09 20:35:21 +0200

mforets gravatar image

updated 2017-06-09 20:37:14 +0200

In integral containing products of bessel functions , the answer after applying the factor method is some expression whose numerator is not "completely factored". For aesthetics or because it is easier to work with, we may want to factor the numerator too.

Is there a way to factor a symbolic expression recursively?

Take this example:

sage: , var x y z
sage: expr = x*y - x*z + 4*z*y*x
sage: factor(expr2)
(4*y*z + y - z)*x
sage: _.operands()[0].factor()
4*y*z + y - z
sage: __.operands()[0].canonicalize_radical() 
(4*y - 1)*z + y
sage: _.factor() 
4*y*z + y - z

so it seems that applying recursively the factor command to the expression tree alone doesn't succeed to get ((4*y - 1)*z + y)*x.

edit retag flag offensive close merge delete



This is for my taste not really a factorization, (after factorizing $x$,) rather a way of extracting the coefficients of a polynomial (w.r.t. one of the variables).

The following can be polished to work recursively, if this is the point,

sage: var( 'x,y,z' );
sage: p = x*y - x*z + 4*z*y*x
sage: p.coefficients( x )
[[4*y*z + y - z, 1]]
sage: p.coefficients?
sage: [ [ q.coefficients(y), xdegree ] 
....:     for q, xdegree in p.coefficients( x ) ]
[[[[-z, 0], [4*z + 1, 1]], 1]]
sage: [ [ r.coefficients(z), xdegree ] 
....:     for r, xdegree in p.coefficients( x ) ]
[[[[y, 0], [4*y - 1, 1]], 1]]

but there is a "human choice" to prefer y or z (in the first factor of a Factorization object). Is this the direction of the question?

dan_fulea gravatar imagedan_fulea ( 2017-06-09 21:28:44 +0200 )edit

yes, that seems useful, thanks. i didn't care so much about a particular choice of one or other factorization, just (as a starter) that a command can reduce the number of summands as much as possible, which didn't happen using factor alone.. and for the use case.. i don't know, take for instance some formulas in electrodynamics)...

mforets gravatar imagemforets ( 2017-06-11 17:32:59 +0200 )edit