Prerequisite: Sympy.solve()
In this article, we will discuss how to solve a linear equation having more than one variable. For example, suppose we have two variables in the equations. Equations are as follows:
x+y =1
x-y =1
When we solve this equation we get x=1, y=0 as one of the solutions. In Python, we use Eq() method to create an equation from the expression.
Syntax : Eq(expression,RHS value)
For example, if we have expression as x+y = 1. It can be written as Eq(x+y,1)
Solving equation with two variables
Construct the equations using Eq() method. To solve the equations pass them as a parameter to the solve() function.
Example :
# importing library sympy
from sympy import symbols, Eq, solve
# defining symbols used in equations
# or unknown variables
x, y = symbols('x,y')
# defining equations
eq1 = Eq((x+y), 1)
print("Equation 1:")
print(eq1)
eq2 = Eq((x-y), 1)
print("Equation 2")
print(eq2)
# solving the equation
print("Values of 2 unknown variable are as follows:")
print(solve((eq1, eq2), (x, y)))
Output:
Equation 1:
Eq(x + y, 1)
Equation 2
Eq(x - y, 1)
Values of 2 unknown variable are as follows:
{x: 1, y: 0}
Solving equation with three variables
Construct the following equations using Eq() and solve then to find the unknown variables.
x +y+z =1
x+y+2z=1
Example:
# importing library sympy
from sympy import symbols, Eq, solve
# defining symbols used in equations
# or unknown variables
x, y, z = symbols('x,y,z')
# defining equations
eq1 = Eq((x+y+z), 1)
print("Equation 1:")
print(eq1)
eq2 = Eq((x-y+2*z), 1)
print("Equation 2")
print(eq2)
eq3 = Eq((2*x-y+2*z), 1)
print("Equation 3")
# solving the equation and printing the
# value of unknown variables
print("Values of 3 unknown variable are as follows:")
print(solve((eq1, eq2, eq3), (x, y, z)))
Output:
Equation 1:
Eq(x + y + z, 1)
Equation 2
Eq(x - y + 2*z, 1)
Equation 3
Values of 3 unknown variable are as follows:
{x: 0, y: 1/3, z: 2/3}