简体   繁体   中英

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])

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.]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM