Archive
Posts Tagged ‘equation’
How to solve a two-variable equation with Sympy
December 13, 2024
Leave a comment
Problem
You have a two-variable equation and you want to solve it with Python / Sympy.
Solution
Let’s see this example:
7x + 9y = 8
9x - 8y = 69
What is the value of ‘x’ and ‘y’?
We could solve it manually too, of course, but let’s say we have hundreds of these. So let’s solve it with Python using the Sympy library.
>>> import sympy as sp
>>>
>>> x = sp.symbols('x')
>>> y = sp.symbols('y')
>>>
>>> eq1 = sp.Eq(7 * x + 9 * y, 8)
>>> eq2 = sp.Eq(9 * x - 8 * y, 69)
>>>
>>> system = [eq1, eq2]
>>>
>>> sol_set = sp.linsolve(system, x, y)
>>> sol_set
{(5, -3)}
>>>
>>> 7 * 5 + 9 * (-3)
8
>>> 9 * 5 - 8 * (-3)
69
