# how to factorize an expression with constant variables ?

Hello, I would like to factorize an expression with sage that contains constant variables (i.e. parameters), but I cannot figure out how to do that.

Here is an example : x, y are variables and A is a parameter

var('A x y')

f = A*x + x + A^2*exp(y) + y
print (f.factor())


Sage returns A^2*e^y + A*x + x + y. Instead, I would like that sage returns (A+1)*x + (A^2+1)*exp(y).

How to do that ? Thank you

edit retag close merge delete

Sort by ยป oldest newest most voted

To get the coefficient of each monomial, try using the list command.

R.<A> = QQ[]
R.<x,y> = PolynomialRing(QQ[A],order='deglex')
f3 = A*x^2 + x^2 + A^2*x + 2*x + x*y+3*x^2*y
list(f3)


This gives:

[(3, x^2*y), (A + 1, x^2), (1, x*y), (A^2 + 2, x)]


I'm not sure if this is exactly what you want, though.

more

'collect' works pretty well in the example I gave :

var('A x y')
f1 = A*x + x + A^2*exp(y) + exp(y)
print f1.collect(A).collect(x).collect(e^y)

--> (A + 1)*x + (A^2 + 1)*e^y


but unfortunately it also performs factorization with cross-products

var('A x y')
f2 = A*x^2 + x^2 + A^2*x + 2*x + x*y
print f2.collect(A).collect(x*y).collect(x)

--> (A + 1)*x^2 + (A^2 + y + 2)*x


whereas I would like to get the coefficient of each monomial x^i*y^j, as obtained with the following example

R.<A> = QQ[]
R.<x,y> = PolynomialRing(QQ[A],order='deglex')
f3 = A*x^2 + x^2 + A^2*x + 2*x + x*y
print f3

--> (A + 1)*x^2 + x*y + (A^2 + 2)*x


Is there a solution to do so ? Thanks

more

Try (f.collect(A)).collect(x).

more