0

假设我有一个 matix

x = [[0,x01,x02,x03],
     [x10,0,x12,0],
     [x20,x21,0,x23],
     [x30,0,x32,0]]
x[i][j]>=0
b = [5,-4,5,-6]

我正在寻找一种简单的方法来找出 x 的一个值,以确保

x[i][0]+x[i][1]+x[i][2]+x[i][3]-x[0][i]-x[1][i]-x[2][i]-x[3][i] == b[i]

我尝试了很多方法,但都失败了。可能的答案是

 x = [[0,4,0,1],
     [0,0,0,0],
     [0,0,0,5],
     [0,0,0,0]]

谢谢你。

4

1 回答 1

1

正如@Blckknght 指出的那样,您必须设置一些约束,否则您将获得多种解决方案。但是硬编码一些东西来让它工作很容易,只是一些矩阵操作。

>>> from numpy import *
>>> from scipy import optimize
>>> def f1(p, b=array([5,-4,5,-6])):
    mp=matrix(array(p).reshape((4,4))) #or reshape((b.size, b.size))
    return sum(array(dot(mp-mp.T, array([1,1,1,1]))-b)**2) #or ones((b.size,))

>>> optimize.fmin(f1, range(16))
Optimization terminated successfully.
         Current function value: 0.000000
         Iterations: 467
         Function evaluations: 743
array([  8.55102418e-04,   1.19481331e+00,   9.84510105e-01,
         3.42579838e+00,   3.37327593e+00,   3.95448146e+00,
         1.18750846e+01,   8.73475559e+00,   5.64496730e+00,
         9.28651143e+00,   9.33505858e+00,   1.59977154e+01,
        -8.41311844e+00,   1.75017928e+01,   1.30696514e+01,
         1.46774131e+01])

必须有一些更好的方法来做到这一点,但要限制值int可以通过很少的变化来完成:

>>> def f1(p, b=array([5,-4,5,-6])):
    mp=matrix(array(p).round().reshape((4,4))) #or reshape((b.size, b.size))
    return sum(array(dot(mp-mp.T, array([1,1,1,1]))-b)**2) #or ones((b.size,))

>>> rlist=[]
>>> for i in range(-500, 500): #constrain to a desired range, and just get the one of the possible answers
    q=optimize.fmin(f1, range(i, i+16), disp=False).round()
    rlist.append((q, f1(q)))
    if f1(q)==0:
        break   
>>> rlist[-1]
(array([-501., -498., -495., -493., -497., -499., -494., -492., -496.,
        -491., -494., -487., -498., -490., -490., -489.]), 0.0)

>>> rlist[-1][0].reshape((4,4))
array([[-501., -498., -495., -493.],
       [-497., -499., -494., -492.],
       [-496., -491., -494., -487.],
       [-498., -490., -490., -489.]])

严格来说,它们仍然存在float,但没关系。用于_int()转换。

于 2013-09-15T00:54:47.137 回答