# Using numerical solution from system of equations I want to take the numerical solution of a variable in a system of equations and use it later in the program. But all I can get is the symbolic definition. Here's a simplified example of the problem.

sage: var('x y z')

sage: eq1 = x + y + z == 6

sage: eq2 = 2*x - y + 2*z == 6

sage: eq3 = 3*x + 3*y - z == 6

sage: solve([eq1, eq2, eq3], x, y, z)

sage: v = x

sage: print v


Output:

[
[x == 1, y == 2, z == 3]
]
x


I assume the syntax for solving the system is correct because I get the right answers but I want v = 1, not v = x. Thanks.

edit retag close merge delete

Sort by » oldest newest most voted

Hi RAC,

You're almost there -- you just need to save the output of the solve command:

sage: solutions = solve([eq1, eq2, eq3], x, y, z)
sage: print solutions
[
[x == 1, y == 2, z == 3]
]
sage: print solutions
[x == 1, y == 2, z == 3]
sage: soln = solutions
sage: print soln
x == 1


The output is a list, whose contents are solutions and multiplicities. In this case the solution has multiplicity 1, so the list contains a single item, which is another list -- that list is the list of expressions which constitutes a solution. solutions is the first item of solutions -- that is, the solution. soln is the first item of that solution -- that is, the expression which gives the value of x:

sage: type(soln)
<type 'sage.symbolic.expression.Expression'>


Now to get the value itself, you need to just take the right hand side of that expression:

sage: expr = soln
sage: expr.rhs()
1
sage: expr.lhs()
x


Note that you don't have to define all these intermediate variables if you don't want to -- I just did it to make the explanation a little clearer:

sage: solve([eq1, eq2, eq3], x, y, z).rhs()
1


Using the other entries in the soln list will give the values of the other variables:

sage: soln.rhs()
2
sage: soln.rhs()
3

more

I see what you are doing. Remember, Sage is Python too! So x is still x. Just because you showed a solution doesn't mean that x was actually assigned to 1. If you want that, you'll have to explicitly say so. There are a few ways to do this, but

sage: sols = solve([eq1, eq2, eq3], x, y, z,solution_dict=True)
sage: v = x.subs(sols)
sage: v
1
sage: x
x


is one way. Notice that here x is still x and v has your solution.

Let us know if this answers the question you have.

more

Yeah, but yours is more comprehensive, though you don't mention how to substitute. We need a union of the answers...

Great, thanks for the help. I'm a social scientist who's trying to teach himself sage and python (and to use it for my work). The last time I had a computer science course Pascal was the in thing ;) RAC

more

If you like the answers, or they answer your question, feel free to click them up/check them.