简体   繁体   English

如何在Python中找到x以确保sum(row [i])-sum(clo [i])= bi?

[英]How to find x to make sure sum(row[i])-sum(clo[i])=bi in python?

Suppose I have a matix 假设我有一个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]

I am looking for an easy way to find out one value for x to make sure that 我正在寻找一种简单的方法来找出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]

I have tried many methods, but all failed. 我尝试了很多方法,但都失败了。 Possible answer is like 可能的答案就像

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

Thank you. 谢谢。

You must set some constrains or you will get multiple solutions as @Blckknght pointed out. 您必须设置一些约束,否则您将获得多个解决方案,如@Blckknght所指出的。 But hard code some stuff to get it work is easy, just some matrix manipulations. 但是,硬编码一些使它起作用的东西很容易,只需进行一些矩阵操作即可。

>>> 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])

There must be some better way to do it, but to constrain the values to int can be done with very little change: 必须有一些更好的方法,但是只需很少的更改即可将值约束为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.]])

Strictly speaking they are still float but that's ok. 严格来说,它们仍然是float但是还可以。 Use _int() to convert. 使用_int()进行转换。

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

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