【问题标题】:How to solve linear equations with parametrization?如何通过参数化求解线性方程组?
【发布时间】:2019-03-03 16:33:30
【问题描述】:

我正在尝试以这种方式解决我的方程式:

a = np.array([[1,2,4,1,0,2],[0,1,2,0,0,1],[0,0,0,2,2,0],[0,0,0,0,14,4],[0,0,0,0,0,-2]])
b = np.array([3,0,1,0,14])
x = np.linalg.solve(a,b)

但是,由于它们不是完整的排名,因此没有唯一的解决方案,而是无穷无尽的解决方案。通常我会在解决这个问题时简单地插入一个参数,比如 x3 = t。然后我有一个解决方案,其中 x2 和 x1 也可以包含 t。但是我怎么能告诉python以这种方式解决它呢?或者至少告诉它 x3 是 t 并继续使用它?

我知道有最小二乘法,但这不是我想要的。

编辑:解决方案看起来像这样:x6 == -7 && x5 == 2 && x4 == -(3/2) && x2 == 7 - 2 x3 && x1 == 9/2 - 使用 Mathematica 制作。只是想知道如何在python中达到同样的效果。

【问题讨论】:

    标签: python numpy linear-equation


    【解决方案1】:

    使用SymPy

    import numpy as np
    import sympy as sym
    
    a = np.array([[1,2,4,1,0,2],[0,1,2,0,0,1],[0,0,0,2,2,0],[0,0,0,0,14,4],[0,0,0,0,0,-2]])
    b = np.array([3,0,1,0,14])
    num_equations, num_variables = a.shape
    
    x = sym.symarray('x', num_variables)
    solution = sym.solve([sym.Eq(ax-b) for ax, b in zip(np.dot(a, x), b)])
    print(solution)
    

    产量

    {x_5: -7, x_4: 2, x_3: -3/2, x_1: -2*x_2 + 7, x_0: 9/2}
    

    【讨论】:

      【解决方案2】:

      这有数学方面和编程方面。在数学方面,需要注意的是,如果 ax=b 有多个解,那么这些解是 {y + b1 * t1 + b_2 * t_2 + ... + bN * tN | t1, ..., tN in the real numbers} 其中 y 是 ax=b 的任意解(例如最小二乘解),b1, ..., bN 是 a 的零空间的基向量。在编程方面,np.linalg.lstsq 获得最小二乘解,scipy.linalg.null_space 获得空空间。您可以将它们组合在一起以获得类似于您想要的输出的一种方法如下。

      import numpy as np
      import scipy.linalg
      import sys
      
      
      def print_parameterized_form(a, b):
          one_solution = np.linalg.lstsq(a, b, rcond=None)[0]
          null_space_basis = scipy.linalg.null_space(a)
          for i in range(a.shape[1]):
              sys.stdout.write('x{} = {}'.format(i, one_solution[i]))
              for j in range(null_space_basis.shape[1]):
                  sys.stdout.write(' + ({}) * t{}'.format(null_space_basis[i, j], j))
              sys.stdout.write('\n')
      
      a = np.array([[1,2,4,1,0,2],[0,1,2,0,0,1],[0,0,0,2,2,0],[0,0,0,0,14,4],[0,0,0,0,0,-2]])
      b = np.array([3,0,1,0,14])
      
      print_parameterized_form(a, b)
      

      这应该给你这样的东西:

      x0 = 4.500000000000011 + (-3.5160449919006082e-15) * t0
      x1 = 1.4000000000000128 + (0.8944271909999162) * t0
      x2 = 2.7999999999999887 + (-0.4472135954999573) * t0
      x3 = -1.499999999999997 + (9.065580383436411e-17) * t0
      x4 = 2.0000000000000004 + (4.62652890306841e-18) * t0
      x5 = -6.999999999999999 + (1.86607760441072e-16) * t0
      

      【讨论】:

      • 我明白了,但这对于非整数矩阵化并不理想。它对我有用,但我不得不想知道为什么像 python/numpy/scipy 这样大的东西还没有办法做到这一点,不像数学。在你使用python的情况下,这些问题不是经常遇到吗?还是使用其他工具代替?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多