如何为python准备方程式系统

如何为python准备方程式系统,python,linear-algebra,Python,Linear Algebra,这是一个非常好的演示,演示了如何在一个简化的情况下——在三个方程和三个变量的情况下 假设我想解决以下系统 对于变量f1、x1和x2。由于这是一个相当小的系统,我可以很容易地手动完成。但这是一个简化的例子——实际上,我的系统由100个变量和100个方程组成 所以我的问题是如何分离变量来解决这个系统?如何在一个向量中收集所有变量并重写系统,以便我可以解决它? 最后,我想要的是f1、x1和x2的数值 注:我只是通过插入随机数来创建这个系统。我不确定这个系统是否能解决,但是。。。你明白了。(在这种情况

这是一个非常好的演示,演示了如何在一个简化的情况下——在三个方程和三个变量的情况下

假设我想解决以下系统

对于变量f1、x1和x2。由于这是一个相当小的系统,我可以很容易地手动完成。但这是一个简化的例子——实际上,我的系统由100个变量和100个方程组成

所以我的问题是如何分离变量来解决这个系统?如何在一个向量中收集所有变量并重写系统,以便我可以解决它? 最后,我想要的是f1、x1和x2的数值


注:我只是通过插入随机数来创建这个系统。我不确定这个系统是否能解决,但是。。。你明白了。(在这种情况下调整数值)。

据我所知,您必须调整系统的矩阵,以处理当前位于右侧的
RyA
和其他变量。您可以手动操作(在这种情况下,此问题不在本网站的范围内,它纯粹是数学练习),或者使用例如,而不是
np.linalg.solve()
,它可以为您完成问题的代数部分:

from sympy import Matrix, symbols, solve

x1, x2, f1 = symbols('x1 x2 f1')
X = Matrix([0, x1, x2])
B = Matrix([f1, 50, 60])
M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

solve(M * X - B, [x1, x2, f1])

# {f1: 40, x2: 100/3, x1: -30}
请注意,
symphy
在求解数值线性系统时可能比
numpy.linalg
慢,因此您可能希望使用
symphy
来完成代数部分的工作,计算矩阵和右侧,然后使用
numpy.linalg.solve
来求解它

import numpy as np
from sympy import expand
def symbolic_to_matrix(F, variables):

    """
    F is a symbolic vector function that is a left hand side of equation F = 0
    variables is a list of variables (sympy.Symbol's) which F depends on.

    Assuming that there exists numeric matrix A such that equation F = 0
    is equivalent to linear equation Ax = b, this function returns 
    tuple (A, b)
    """
    A = []
    b = []
    for row in F:
        coeffs = expand(row).as_coefficients_dict()
        A.append([float(coeffs[x]) for x in variables])
        b.append(-float(coeffs[1]))
    return np.array(A), np.array(b)

A, b = symbolic_to_matrix(M * X - B, [x1, x2, f1])
# A
# array([[ 2.,  3., -1.],
#       [ 5.,  6.,  0.],
#       [ 8.,  9.,  0.]])
# b
# array([ -0.,  50.,  60.])

np.linalg.solve(A, b)
# array([-30.        ,  33.33333333,  40.        ])
# the same 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]]
     """
     for i in equations:
          if len(i)<>(len(equations)+1):
               raise ValueError("your equation system has not a valid format")
     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=-1
          for i in range(len(equations)):
               if equations[i][0]<>0:
                    index=i;
                    break;
          if index==-1:
               raise ValueError("your equation system can not be solved")
          #print "index "+str(eq)+": ",index
          #for the equation[index] calc the lists next item  as follows
          lists.append([-1.0*i/equations[index][0] for i in equations[index][1:]])
          #print "list"+str(eq)+": ", lists[-1]
          #remove 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
def求解(方程):
"""
线性方程组的常数存储在系统中每个方程的列表中
例如,下面的系统:
2x+9y-3z+7w+8=0
7x-2y+6z-1w-10=0
-8x-3y+2z+5w+4=0
0x+2y+z+w+0=0
以列表形式表示:
[[2,9,-3,7,8],[7,-2,6,-1,-10],[-8,-3,2,5,4],[0,2,1,1,0]]
"""
对于方程中的i:
如果len(i)(len(方程)+1):
raise VALUE ERROR(“您的方程式系统的格式无效”)
lists=[]#我没有给它起个有意义的名字
对于范围内的等式(len(方程式)):
#打印“方程式1”,方程式
#找到一个第一个元素不是零的方程,称之为索引
索引=-1
对于范围内的i(len(方程)):
如果方程[i][0]0:
指数=i;
打破
如果索引==-1:
raise VALUE ERROR(“您的方程组无法求解”)
#打印“索引”+str(eq)+“:”,索引
#对于等式[索引]计算,下一项列出如下
列表.附加([-1.0*i/等式[index][0]表示等式[index][1:][1]中的i)
#打印“列表”+str(eq)+“:”,列表[-1]
#删除方程式[索引]并修改其他方程式
方程式.pop(索引)
对于方程中的i:
对于范围内的j(len(列表[-1])):
i[j+1]+=i[0]*列表[-1][j]
i、 流行音乐(0)
list.reverse()
答案=[列表[0][0]]
对于范围(1,len(列表))中的i:
tmpans=列表[i][1]
对于范围内的j(len(列表[i])-1):
tmpans+=列表[i][j]*答案[-1-j]
答案。附加(tmpans)
答案:反向()
答复

W_2、Phi_2、W_3等等,用RyA、rho1、A、L等等来表示,我说得对吗?@IlyaV.Schurov我看得出我不清楚,我的错。不,变量是
variables=[RyA,RMA,W_2,Phi_2,W_3,Phi_3,RyB,Phi_4,W_5,Phi_5]
因此,其中一些位于方程的左侧,而另一些位于右侧。为了使用
numpy.linalg.solve()
,我不得不将变量从一边移到另一边,就像我在5:30时附加的视频一样。你能用数学术语(可能是简化形式)编写你的系统吗?我编辑了这个问题,使它更清晰和简单。我编辑了我的操作,这样问题现在就更清楚了。我认为你的答案是正确的,如果你能把它调整到我的例子…那就太完美了!注:stackoverflow没有乳胶,我投了很大的反对票。我根据你更正的问题更正了一个答案。我添加了一个示例,说明sympy如何与numpy互动以提高性能。