Defining Equations

Using symbolic math variables we can define equations using SymPy. Equations in SymPy are different than expressions. An expression does not have equality. An equation has equality.


In [28]:
from sympy import symbols, Eq, solveset, solve
from sympy.solvers.solveset import linsolve

In [29]:
x, y = symbols('x y')

SymPy equations are instantiated as object of the Eq class. Once Sympy symbols are created, they can be passed into an equation object. Let's create the equation:

$$ 4x + 2y - 3 = $$

In [30]:
eq1 = Eq(4*x+2*y - 3)

Now let's create a second equation:

$$ -2x - 6y + 10 = 0 $$

In [1]:
eq2 = Eq(-2*x-6*y + 10)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-4a2c3420076e> in <module>()
----> 1 eq2 = Eq(-2*x-6*y + 10)

NameError: name 'Eq' is not defined

To solve the two equations for the two variables x and y, use Sympy's solve() function. The function takes two arguments, a tuple of the equations (eq1, eq2) and a tuple of the variables to solve for (x, y).


In [2]:
sol = solve((eq1, eq2),(x, y))
sol


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-038f02142922> in <module>()
----> 1 sol = solve((eq1, eq2),(x, y))
      2 sol

NameError: name 'solve' is not defined

The SymPy solution object is a dictionary. The keys are the SymPy variable objects and the values are the numerical values these variables correspond to.


In [3]:
print(f'The solution is x = {sol[x]}, y = {sol[y]}')


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-82f40b20ea0e> in <module>()
----> 1 print(f'The solution is x = {sol[x]}, y = {sol[y]}')

NameError: name 'sol' is not defined

In [ ]: