简体   繁体   中英

Solving simultaneous equations with Python

Can anyone tell me the python code to solve the equation:

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

I have the following code but it isn't working:

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)

The problem is how you formatted the missing variables for the equations, remember that you should use 0 instead of nothing, otherwise the arrays (equations) get misinterpreted and provide you a wrong answer/error:

This should work for you now:

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)

Output:

[-0.15384615 -0.30769231  0.76923077  0.84615385]

An alternative approach uses sympy, Python's symbolic mathematics package:

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 })

This prints:

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

It is even possible to directly take the string input and find a solution:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM