使用 SymPy 求解一组 4 个符号方程时的 AttributeError

AttributeError in solving a set of 4 symbolic equation using SymPy

我想求解如下的 4 方程组:

x1 = b1*a1 + b2*a2 + b3*a3 + b4*a4   
x2 = b1*a5 + b2*a6 + b3*a7 + b4*a8  
x3 = b1*a9 + b2*a10 + b3*a11 + b4*a12  
x4 = b1*a13 + b2*a14 + b3*a15 + b4*a16

我的目标是找到一个解决方案,使 b1、b2、b3、b4 由另一个定义 parameters/symbols。

我的尝试是:

import sympy as sy
sy.init_printing()

x1, x2, x3, x4, b1, b2, b3, b4, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14,
a15, a16 = sy.symbols('x1, x2, x3, x4, b1, b2, b3, b4, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
a11, a12, a13, a14, a15, a16')

print(sy.solve(((x1-b1*a1-b2*a2-b3*a3-b4*a4, x2-b1*a5-b2*a6-b3*a7-b4*a8, 
x3-b1*a9-b2*a10-b3*a11-b4*a12,x4-b1*a13-b2*a14-b3*a15-b4*a16), [b1,b2,b3,b4])))

问题是我收到以下错误:

print(sy.solve(((x1-b1*a1-b2*a2-b3*a3-b4*a4, x2-b1*a5-b2*a6-b3*a7-b4*a8, x3-b1*a9-b2*a10-b3*a11-b4*a12,x4-b1*a13-b2*a14-b3*a15-b4*a16), [b1,b2,b3,b4])))
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\solvers\solvers.py", line 858, in solve
symbols = set().union(*[fi.free_symbols for fi in f])
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\solvers\solvers.py", line 858, in <listcomp>
symbols = set().union(*[fi.free_symbols for fi in f])
AttributeError: 'list' object has no attribute 'free_symbols'

如何修复代码?

您在不应该出现的方程式周围加上了额外的括号。这是一个更简单的例子:

import sympy as sym

x, y = sym.symbols('x, y')

print(sym.solve(((x + y, x - y - 1), [x, y])))

解决方法是删除这些括号:

print(sym.solve((x + y, x - y - 1), [x, y]))

这样您就可以将两个参数传递给 solve。一个是方程组,另一个是符号列表。以前您将一个参数作为元组传递。

解决这个问题并整理您的代码可以得到:

import sympy as sym
sym.init_printing()

(
 x1, x2, x3, x4,
 b1, b2, b3, b4,
 a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16,
) = sym.symbols('x1:5 b1:5 a1:17')

equations = [
    x1 - b1*a1  - b2*a2  - b3*a3  - b4*a4,
    x2 - b1*a5  - b2*a6  - b3*a7  - b4*a8,
    x3 - b1*a9  - b2*a10 - b3*a11 - b4*a12,
    x4 - b1*a13 - b2*a14 - b3*a15 - b4*a16,
]
unknowns = [b1, b2, b3, b4]

solution = sym.solve(equations, unknowns)

print(solution)

请注意,您也可以像 Eq(x1, b1*a1 + ...) 一样使用 Eq,对于线性系统,最好使用 linsolve 而不是 solve