簡體   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?

假設我有一個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]]

謝謝。

您必須設置一些約束,否則您將獲得多個解決方案,如@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()進行轉換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM