Ask Your Question

Constant coefficient of symbolic expression

asked 2020-08-11 08:50:59 +0200

philipp7 gravatar image

updated 2020-08-11 09:03:53 +0200

Suppose we have the following

sage: var("x,y,z")
sage: expr = x*y+z^2+4

I am looking for a function which does something like

sage: expr.constant_coefficient()

However, I did not find such a function. If I use coefficient I can get the desired result using

sage: expr.coefficient(x,0).coefficient(y,0).coefficient(z,0)

Of course if I have more variables that gets more tedious and I'd write a small helper function which goes through the variables contained in expr. I feel like this is much too complicated and I'm just overlooking some function. Is anyone aware of some cleaner way to do this if the expression contains a lot of variables (i.e. without having to write a helper-function)?

Thank you for your help!

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2020-08-11 09:05:13 +0200

rburing gravatar image

updated 2020-08-11 09:14:13 +0200

You can set all variables to zero:

sage: var("x,y,z")
sage: expr = x*y+z^2+4
sage: expr.subs({v : 0 for v in expr.variables()})

If you are working with polynomials, consider using polynomial ring instead:

sage: R.<x,y,z> = PolynomialRing(QQ)
sage: expr = x*y+z^2+4
sage: expr.constant_coefficient()

Also you can convert back and forth between symbolic expressions and polynomials:

sage: var("x,y,z")
sage: expr = x*y+z^2+4
sage: R = PolynomialRing(QQ, names='x,y,z')
sage: SR(R(expr).constant_coefficient())
edit flag offensive delete link more


Thanks! I thought about setting the variables to 0 as well but clearly that expression gets very ugly and hard to read. Converting to polynomials is a great way to do it, thanks!

philipp7 gravatar imagephilipp7 ( 2020-08-11 09:09:18 +0200 )edit

You're welcome! (I updated the answer to make the substitution method more readable.)

rburing gravatar imagerburing ( 2020-08-11 09:15:20 +0200 )edit

Possible shortcut:

sage: expr.polynomial(ZZ).constant_coefficient()


Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2020-08-11 09:40:38 +0200 )edit

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: 2020-08-11 08:50:59 +0200

Seen: 875 times

Last updated: Aug 11 '20