简体   繁体   English

用python求解方程组

[英]Solving system of equations in python

How do I solve simple system of equation like the following in python? 如何在python中解决以下简单的方程式系统?

x = (2/3)*y + (1/3)*0 x =(2/3)* y +(1/3)* 0

y = (2/3)*1 + (1/3)*x y =(2/3)* 1 +(1/3)* x

I tried SymPy but couldn't figure it out. 我尝试过SymPy,但无法解决。

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)} 输出:{(0.571428571428571,0.857142857142857)}

Type is 'sympy.sets.sets.FiniteSet' 类型为'sympy.sets.sets.FiniteSet'

How do I extract just the x value to set as a variable? 如何仅提取x值设置为变量?

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 使用numpy python模块

Example solving following system of linear equation 求解线性方程组的示例

Case 1: 情况1:

24a + 4b = 35 24a + 4b = 35

8a + 4b = 94 8a + 4b = 94

Case 2: 情况2:

a + b = 4 a + b = 4

2a + b = 8 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.]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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