2.4.1 Solving Equations

The solve function solves equations. To use it, first specify some variables; then the arguments to solve are an equation (or a system of equations), together with the variables for which to solve:

sage: x = var('x')
sage: solve(x^2 + 3*x + 2, x)
[x == -2, x == -1]

You can solve equations for one variable in terms of others:

sage: x, b, c = var('x b c')
sage: solve([x^2 + b*x + c == 0],x)
[x == (-sqrt(b^2 - 4*c) - b)/2, x == (sqrt(b^2 - 4*c) - b)/2]

You can also solve for several variables:

sage: x, y = var('x, y')
sage: solve([x+y==6, x-y==4], x, y)
[[x == 5, y == 1]]

The following example of using Sage to solve a system of non-linear equations was provided by Jason Grout: first, we solve the system symbolically:

sage: var('x y p q')
(x, y, p, q)
sage: eq1 = p+q==9
sage: eq2 = q*y+p*x==-6
sage: eq3 = q*y^2+p*x^2==24
sage: solve([eq1,eq2,eq3,p==1],p,q,x,y)
[[p == 1, q == 8, x == (-4*sqrt(10) - 2)/3, y == (sqrt(2)*sqrt(5) - 4)/6],
 [p == 1, q == 8, x == (4*sqrt(10) - 2)/3, y == (-sqrt(2)*sqrt(5) - 4)/6]]

For a numerical solution, you can instead use:

sage: solns = solve([eq1,eq2,eq3,p==1],p,q,x,y, solution_dict=True)
sage: [[s[p].n(30), s[q].n(30), s[x].n(30), s[y].n(30)] for s in solns]
[[1.0000000, 8.0000000, -4.8830369, -0.13962039],
 [1.0000000, 8.0000000, 3.5497035, -1.1937129]]
(The function n prints a numerical approximation, and the argument is the number of bits of precision.)

See About this document... for information on suggesting changes.