如何用Python解方程组(3个例子)

240 阅读2分钟

为了解决Python中的方程组,我们可以使用NumPy库的函数。

下面的例子展示了如何使用NumPy来解决Python中几个不同的方程组。

例1:求解双变量方程组

假设我们有以下方程组,我们想求出x和y的值。

5x + 4y = 35

2x + 6y = 36

下面的代码显示了如何使用NumPy来解决x和y的值:

import numpy as np

#define left-hand side of equation
left_side = np.array([[5, 4], [2, 6]])

#define right-hand side of equation
right_side = np.array([35, 36])

#solve for x and y
np.linalg.inv(left_side).dot(right_side)

array([3., 5.])

这告诉我们,x的值是3,y的值是5

例2:求解三变量的方程组

假设我们有以下的方程组,我们想求出x、y和z的值。

4x + 2y + 1z = 34

3x + 5y - 2z = 41

2x + 2y + 4z = 30

下面的代码显示了如何使用NumPy来解决x、y和z的值:

import numpy as np

#define left-hand side of equation
left_side = np.array([[4, 2, 1], [3, 5, -2], [2, 2, 4]])

#define right-hand side of equation
right_side = np.array([34, 41, 30])

#solve for x, y, and z
np.linalg.inv(left_side).dot(right_side)

array([5., 6., 2.])

这告诉我们,x的值是5,y的值是6,z的值是2

例3:求解四个变量的方程组

假设我们有以下的方程组,我们想求出w、x、y和z的值。

6w + 2x + 2y + 1z = 37

2w + 1x + 1y + 0z = 14

3w + 2x + 2y + 4z = 28

2w + 0x + 5y + 5z = 28

下面的代码显示了如何使用NumPy来解决w、x、y和z的值:

import numpy as np

#define left-hand side of equation
left_side = np.array([[6, 2, 2, 1], [2, 1, 1, 0], [3, 2, 2, 4], [2, 0, 5, 5]])

#define right-hand side of equation
right_side = np.array([37, 14, 28, 28])

#solve for w, x, y, and z
np.linalg.inv(left_side).dot(right_side)
 
array([4., 3., 3., 1.])

这告诉我们,w的值是4,x是3,y是3,z是1

其他资源

下面的教程解释了如何使用其他统计软件解方程组:

如何在R中求解方程组
如何在Excel中求解方程组