有没有一个Python模块可以解决线性方程?

47

我想解决一个三个或更多变量的线性方程,有没有一个好的Python库可以做到这一点?


1
未经测试,但是可以访问以下链接:http://docs.sympy.org/dev/modules/solvers/solvers.html - Thomas K
6个回答

70

2
我能使用np.linalg.solve(a, b)函数在Galois场上求解模2方程组吗?或者如果您知道另一个可以解决这个问题的软件包,那将非常有帮助 :) - giliev
5
NumPy的“solve”无法解决方程组中方程个数大于变量个数的情况(这是我的使用场景)。因此,请改用SymPy。 - Bitcoin Cash - ADA enthusiast


9
您可以在Python中使用最小二乘法来解决方程组,例如解决方程式3x+4y=75x+6y=8
>>> import numpy
>>> a=[[3,4],[5,6]]
>>> b=[7,8]
>>> numpy.linalg.lstsq(a,b)
(array([-5. ,  5.5]), array([], dtype=float64), 2, array([ 9.27110906,  0.21572392]))

8

使用 @Jeremy 的示例:

from sympy import *
x0, x1 = symbols(['x0', 'x1'])
sol = solve([3 * x0 + x1 - 9, x0 + 2 * x1 - 8], [x0, x1])
print(sol)

输出:

{x0: 2, x1: 3}

使用稍有不同的符号来演示@004的例子:

from sympy import *
x, y = symbols(['x', 'y'])
system = [
    Eq(3*x + 4*y, 7),
    Eq(5*x + 6*y, 8)
]
soln = solve(system, [x, y])
print(soln)

{x: -5, y: 11/2}

注意:有时候你会看到下面这种符号表示法:x,y = symbols('x,y'),它似乎不太符合Python的风格。


2

你可以编写一个简单的函数来解决线性方程组。

Original Answer翻译成"最初的回答"。
def solve(equations):
     #the constants of a system of linear equations are stored in a list for each equation in the system
     """
     for example the system below:
          2x+9y-3z+7w+8=0
          7x-2y+6z-1w-10=0
          -8x-3y+2z+5w+4=0
          0x+2y+z+w+0=0
     is expressed as the list:
          [[2,9,-3,7,8],[7,-2,6,-1,-10],[-8,-3,2,5,4],[0,2,1,1,0]]
     """
     lists=[] # I failed to name it meaningfully
     for eq in range(len(equations)):
          #print "equations 1", equations
          #find an equation whose first element is not zero and call it index
          index=0
          for i in range(len(equations)):
               if equations[i][0]<>0:
                    index=i;
                    break;
          #print "index "+str(eq)+": ",index
          #for the equation[index] calc the lists next itam  as follows
          lists.append([-1.0*i/equations[index][0] for i in equations[index][1:]])
          #print "list"+str(eq)+": ", lists[-1]
          #remve equation[index] and modify the others
          equations.pop(index)
          for i in equations:
               for j in range(len(lists[-1])):
                    i[j+1]+=i[0]*lists[-1][j]
               i.pop(0)

     lists.reverse()

     answers=[lists[0][0]]
     for i in range(1,len(lists)):
          tmpans=lists[i][-1]
          for j in range(len(lists[i])-1):
               tmpans+=lists[i][j]*answers[-1-j]
          answers.append(tmpans)
     answers.reverse()
     return answers

0

你还可以使用lsq_linear来在x上添加约束(上下限): scipy.optimize.lsq_linear


你应该详细阐述你的回答以引起注意。一个代码示例是最好的策略。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接