如何在python中求解多元线性方程式? [英] How can I solve multivariable linear equation in python?

查看:130
本文介绍了如何在python中求解多元线性方程式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有10,000个变量.对于其中的100个,我确实知道确切的值.

I have 10,000 variables. for 100 of them, I do know the exact value.

其他人的给出方式如下:

others are given like:

a = 0.x_1 * b + 0.y_2 * c+ 0.z_1 * d + (1 - 0.x_1 - 0.y_1 - 0.z_1) * a
b = 0.x_2 * c + 0.y_2 * d+ 0.z_2 * e + (1 - 0.x_2 - 0.y_2 - 0.z_2) * b

...

q = 0.x_10000 * p + 0.y_10000 * r+ 0.z_10000 * s + (1 - 0.x_10000 - 0.y_10000 - 0.z_10000) * q

是的,我知道确切值0.x_n,0.y_n,0.z_n ...(以0为前缀的意思是它小于1而大于0)

yes I know exact value of 0.x_n, 0.y_n, 0.z_n ... (the point of having 0. as a prefix means it is less than 1 while bigger than 0)

如何在python中解决此问题?如果您能为我提供一些示例,例如带有这样的简单方程式,我将不胜感激:

How can I solve this in python? I'd really appreciate if you can provide me some example, with simple equations like this :

x - y + 2z =  5
    y -  z = -1
         z =  3

推荐答案

(使用 numpy )如果我们重写线性方程组

(Using numpy) If we rewrite the system of linear equations

x - y + 2z =  5
    y -  z = -1
         z =  3

作为矩阵方程

A x = b

A = np.array([[ 1, -1,  2],
              [ 0,  1, -1],
              [ 0,  0,  1]])

b = np.array([5, -1, 3])

然后可以使用np.linalg.solve找到x:

import numpy as np

A = np.array([(1, -1, 2), (0, 1, -1), (0, 0, 1)])
b = np.array([5, -1, 3])
x = np.linalg.solve(A, b)

收益

print(x)
# [ 1.  2.  3.]

我们可以检查A x = b:

print(np.dot(A,x))
# [ 5. -1.  3.]

assert np.allclose(np.dot(A,x), b)

这篇关于如何在python中求解多元线性方程式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆