Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 818
RC07JNR Avatar asked Nov 15 '19 14:11

RC07JNR


People also ask

How do you solve two equations with two variables in Python?

To solve the two equations for the two variables x and y , we'll use SymPy's solve() function. The solve() function takes two arguments, a tuple of the equations (eq1, eq2) and a tuple of the variables to solve for (x, y) . The SymPy solution object is a Python dictionary.

Can I use Python to solve equations?

Sympy is a package for symbolic solutions in Python that can be used to solve systems of equations. The same approach applies to linear or nonlinear equations.


1 Answers

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]
like image 72
Celius Stingher Avatar answered Sep 30 '22 08:09

Celius Stingher