# Get the constant value of an equation

This post is a wiki. Anyone with karma >750 is welcome to improve it.

I have the following equation :

(x - 1)^2 - (x - 2)^2 - (y - 1)^2 + y^2 + (z - 3)^2 - (z - 4)^2 == 1.75000000000000


which I factorized to :

2*x + 2*y + 2*z - 51/4


And then I would like to extract the -51/4 but the .coefficient() function doesn't work for constant so I have no idea to get the constant value.

edit retag close merge delete

You can define f(x,y,z)=2*x + 2*y + 2*z - 51/4 and then find f(0,0,0).

( 2017-10-07 20:51:29 +0200 )edit

Oh yes, that's a good idea ! Thanks a lot

( 2017-10-07 21:15:23 +0200 )edit

Sort by » oldest newest most voted

In order to extract "by code" (not "by eyes"), there should be clear which is the general input. Let us assume we have a general polynomial equation eq. Then eq.lhs() - eq.rhs() is a polynomial and we have only to extract its free coefficient. To get the right method, it is worth to convert it to a true sage polynomial. As it comes, it is rather an expression.

Here is a more detailed dialog with the sage interpreter for our present case.

sage: var( 'x,y,z' );
sage: eq = (x - 1)^2 - (x - 2)^2 - (y - 1)^2 + y^2 + (z - 3)^2 - (z - 4)^2 == 1.75000000000000
sage: eq = eq.simplify_full()
sage: eq
2*x + 2*y + 2*z - 11 == 1.75
sage: eq = eq.subtract_from_both_sides( eq.rhs() )
sage: eq
2*x + 2*y + 2*z - 12.75 == 0.0
sage: LHS = eq.lhs()
sage: LHS
2*x + 2*y + 2*z - 12.75
# sage: LHS.coefficients?
sage: LHS.coefficients(x,sparse=False)
[2*y + 2*z - 12.75, 2]
sage: LHS.coefficients(x,sparse=False)[0]
2*y + 2*z - 12.75
sage: LHS . coefficients(x,sparse=False)[0] . coefficients(y,sparse=False)[0]
2*z - 12.75
sage: LHS . coefficients(x,sparse=False)[0] . coefficients(y,sparse=False)[0] . coefficients(z,sparse=False)[0]
-12.75


The "quick" way would have been:

sage: var( 'x,y,z' );
sage: eq = (x - 1)^2 - (x - 2)^2 - (y - 1)^2 + y^2 + (z - 3)^2 - (z - 4)^2 == 1.75000000000000
sage: P = eq.lhs() - eq.rhs()
sage: PP = P.polynomial(QQ)
sage: x,y,z = PP.parent().gens()
sage: PP.coefficient( {x:0, y:0, z:0 } )
-51/4


(The "quick" way can be converted rather quickly to a general solution.)

more

Two "brute force" possibilities :

sage: (2*(x+y+z)-51/4).coefficients(x)[0][0].coefficients(y)[0][0].coefficients(
....: z)[0][0]
-51/4
sage: (2*(x+y+z)-51/4).coefficients(x,sparse=False)[0].coefficients(y,sparse=Fal
....: se)[0].coefficients(z,sparse=False)[0]
-51/4


Both can be automated bu looping or reducing on the polynom's variables.

HTH.

more