'Solving system of equations in python
How do I solve simple system of equation like the following in python?
x = (2/3)*y + (1/3)*0
y = (2/3)*1 + (1/3)*x
I tried SymPy but couldn't figure it out.
solved the equation part
from sympy import *
from sympy.solvers.solveset import linsolve
x, y = symbols('x, y')
linsolve([x - 2/3*y, y - 2/3 - 1/3*x ], (x, y))
Output: {(0.571428571428571, 0.857142857142857)}
Type is 'sympy.sets.sets.FiniteSet'
How do I extract just the x value to set as a variable?
Got it.
z = linsolve([x - 2/3*y, y - 2/3 - 1/3*x ], (x, y))
print(z.args[0][0])
Solution 1:[1]
Using numpy python module
Example solving following system of linear equation
Case 1:
24a + 4b = 35
8a + 4b = 94
Case 2:
a + b = 4
2a + b = 8
>>> import numpy as np
>>> a = np.array([[24, 4],[8,4]])
>>> b = np.array([35, 94])
>>> print(np.linalg.solve(a,b))
[-3.6875 30.875 ]
>>> a = np.array([[1, 1],[2,1]])
>>> b = np.array([4, 8])
>>> print(np.linalg.solve(a,b))
[4. 0.]
Solution 2:[2]
sympy has updated to solve() for solving the System of linear Equations. first create equations with Eq() method. and then solve those equations with solve(). linsolve() also still works.
import sympy as sp
from sympy.solvers import solve
eq1= sp.Eq(x-2/3*y-1/3*0)
eq2 = sp.Eq(1/3*x-y+2/3)
output = solve([eq1,eq2],dict=True)
your equations are like this
x?0.666666666666667y=0
0.333333333333333x?y+0.666666666666667=0
output:
[{x:0.571428571428571, y:0.857142857142857}]
once you get the output. output variable type is list. then take the first index 0which is dictionary. then convert it into list type.
values = list(output[0].values())
will give your output like this.
[0.571428571428571, 0.857142857142857]
then
x = values[0] #0.571428571428571
y = values[1] # 0.857142857142857
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | C?t?lin George Fe?til? |
| Solution 2 |
