编程语言
首页 > 编程语言> > 用Python解决线性整数方程组

用Python解决线性整数方程组

作者:互联网

我正在寻找一种方法来解决Python中的线性方程组.
特别是,我正在寻找大于所有零的最小整数向量并求解给定方程.
例如,我有以下等式:

enter image description here

并想解决
enter image description here.

在这种情况下,求解该方程的最小整数向量为
enter image description here.

但是,如何确定该解决方案?
如果我使用scipy.optimize.nnls,例如

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

结果是(array([0.,0.,0.]),0.0).
这也是正确的,但不是所需的解决方案…

编辑:对于某些方面的不精确,我深表歉意.
如果有人对这些细节感兴趣,那么问题出在纸上
“用于数字信号处理的同步数据流程序的静态调度”,Edward A. Lee和David G. Messerschmitt,
IEEE Transactions on Computers,第一卷. C-36,第1号,第24-35页,1987年1月.

定理2说

For a connected SDF graph with s nodes and topology matrix A and with rank(A)=s-2, we can find a positive integer vector b != 0 such that Ab = 0 where 0 is the zero vector.

在定理2证明之后,他们说

It may be desirable to solve for the smallest positive integer vector in the nullspace. To do this, reduce each rational entry in u’ so that its numerator and denominator are relatively prime. Euclid’s algorithm will work for this.

解决方法:

要找到所需的确切解决方案,numpy和scipy可能不是最佳工具.他们的算法通常在浮点中工作,并且不能保证给出确切的答案.

您可以使用sympy获得此问题的确切答案. sympy中的Matrix类提供了nullspace()方法,该方法返回该null空间的基本向量列表.这是一个例子:

In [20]: from sympy import Matrix, lcm

In [21]: A = Matrix([[1, -1, 0], [0, 2, -1], [2, 0, -1]])

获取空空间中的向量. nullspace()返回一个列表;此代码假定A的等级为2,因此列表的长度为1:

In [22]: v = A.nullspace()[0]

In [23]: v
Out[23]: 
Matrix([
[1/2],
[1/2],
[  1]])

在v中找到值的分母的最小公倍数,以便将结果缩放为最小整数:

In [24]: m = lcm([val.q for val in v])

In [25]: m
Out[25]: 2

x持有整数答案:

In [26]: x = m*v

In [27]: x
Out[27]: 
Matrix([
[1],
[1],
[2]])

要将结果转换为整数的numpy数组,可以执行以下操作:

In [52]: np.array([int(val) for val in x])
Out[52]: array([1, 1, 2])

标签:python,numpy,scipy,linear-algebra
来源: https://codeday.me/bug/20191013/1908770.html