gpt4 book ai didi

python - 用 Python 求解联立方程

转载 作者:行者123 更新时间:2023-12-05 00:10:02 28 4
gpt4 key购买 nike

谁能告诉我解方程的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)

最佳答案

另一种方法是使用 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)

关于python - 用 Python 求解联立方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58878594/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com