使用Python解决同步方程组

5

有谁能告诉我解决这个方程的Python代码:

2w + x + 4y + 3z = 5
w - 2x + 3z = 3
3w + 2x - y + z = -1
4x - 5z = -3

我有以下代码,但它无法工作:
A2 = np.array([[2,1,4,3],[1,-2,3],[3,2,-1, 1],[4, -5]])
b2 = np.array([[5,3,-1, -3]]).T 
print('A\n',A2)
print('b\n',b2)
v2 = np.linalg.solve(A2,b2)
print('v')
print(v2)

1
你的系数矩阵(事实上它甚至不像一个矩阵)是错误的。如果方程中没有某个变量,则必须用零填充矩阵。 - Péter Leéh
2个回答

8
问题在于您对方程中缺失变量的格式化方式,记住应该使用0而不是空值,否则数组(方程)会被错误解释并提供错误答案/错误信息:
现在,这应该适用于您:
import numpy as np
A = [[2,1,4,3],[1,-2,0,3],[3,2,-1,1],[0,4,0,5]]
Y = [5,3,-1,3]

res = np.linalg.inv(A).dot(Y)
print(res)

输出:

[-0.15384615 -0.30769231  0.76923077  0.84615385]

7

另一种方法使用sympy,Python的符号数学包:

from sympy import Eq, solve
from sympy.abc import w, x, y, z

sol = solve([ Eq(2*w + x + 4*y + 3*z, 5),
              Eq(w - 2*x + 3*z, 3),
              Eq(3*w + 2*x - y + z, -1),
              Eq(4*x - 5*z, -3) ])
print(sol)
print({ s:sol[s].evalf() for s in sol })

这将打印:

{w: 94/45, x: -20/9, y: 74/45, z: -53/45}
{w: 2.08888888888889, x: -2.22222222222222, y: 1.64444444444444, z: -1.17777777777778}

直接使用字符串输入并找到解决方案也是可能的:

from sympy import Eq, solve
from sympy.parsing.sympy_parser import parse_expr, standard_transformations, implicit_multiplication_application

eqs = ['2w + x + 4y + 3z = 5',
       'w - 2x + 3z = 3',
       '3w + 2x - y + z = -1',
       '4x - 5z = -3']
transformations=(standard_transformations + (implicit_multiplication_application,))
eqs_sympy = [Eq(parse_expr(e.split('=')[0], transformations=transformations),
                parse_expr(e.split('=')[1], transformations=transformations))
             for e in eqs]
sol = solve(eqs_sympy)
print(sol)

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