Numpy: Linear system with specific conditions. No negative solutions

前端 未结 1 1934
闹比i
闹比i 2021-01-22 21:24

I\'m writing a Python code using numpy. In my code I use \"linalg.solve\" to solve a linear system of n equations in n variables. Of course the solutions could be either positiv

相关标签:
1条回答
  • 2021-01-22 22:02

    You have a minimization problem, i.e.

    min ||Ax - b||
    s.t. x_i >= 0 for all i  in [0, n-1]
    

    You can use the Optimize module from Scipy

    import numpy as np
    from scipy.optimize import minimize
    
    A = np.array([[1., 2., 3.],[4., 5., 6.],[7., 8., 10.]], order='C')
    b = np.array([6., 12., 21.])
    n = len(b)
    
    # Ax = b --> x = [1., -2., 3.]
    
    fun = lambda x: np.linalg.norm(np.dot(A,x)-b)
    # xo = np.linalg.solve(A,b)
    # sol = minimize(fun, xo, method='SLSQP', constraints={'type': 'ineq', 'fun': lambda x:  x})
    sol = minimize(fun, np.zeros(n), method='L-BFGS-B', bounds=[(0.,None) for x in xrange(n)])
    
    x = sol['x'] # [2.79149722e-01, 1.02818379e-15, 1.88222298e+00]
    

    With your method I get x = [ 0.27272727, 0., 1.90909091].

    In the case you still want to use your algorithm, it is below

    n = len(b)
    x = np.linalg.solve(A,b)
    pos = np.where(x>=0.)[0]
    
    while len(pos) < n:
        Ap = A[pos][:,pos]
        bp = b[pos]
        xp = np.linalg.solve(Ap, bp)
        x = np.zeros(len(b))
        x[pos] = xp
        pos = np.where(x>=0.)[0]
    

    But I don't recommend you to use it, you should use the minimize option.

    0 讨论(0)
提交回复
热议问题