Solving a Linear Systes of Equations Using python
Solving a Linear Systes of Equations Using python
Solving linear systems of equations is straightforward using the scipy command linalg.solve. This command expects an input matrix and a right-hand-side vector. The solution vector is then computed. An option for entering a symmetrix matrix is offered which can speed up the processing when applicable. As an example, suppose it is desired to solve the following simultaneous equations:

We could find the solution vector using a matrix inverse:
![[ left[ egin{array}{c} x y zend{array} ight]=left[ egin{array}{ccc} 1 & 3 & 5 2 & 5 & 1 2 & 3 & 8end{array} ight]^{-1}left[ egin{array}{c} 10 8 3end{array} ight]=frac{1}{25}left[ egin{array}{c} -232 129 19end{array} ight]=left[ egin{array}{c} -9.28 5.16 0.76end{array} ight].]](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_sPtDNQEmOaTfOxYqvFgsyD_qN0xTlhUY7w5E8WUgDmtZJI2hbBhCBdrmruRpV7Id70apWAHlzmXgw65Sdr4W5wLJKALxx_NNp0L6jeKTGY--_TPDEWGcvQ52KG4LUgTKow9Bz9Sw459Y5KffaA_FcuzPYHWmpiTNDqE4RE86325m7Gz1GKaA=s0-d)
However, it is better to use the linalg.solve command which can be faster and more numerically stable. In this case it however gives the same answer as shown in the following example:
>>> import numpy as np
>>> from scipy import linalg
>>> A = np.array([[1,2],[3,4]])
>>> A
array([[1, 2],
[3, 4]])
>>> b = np.array([[5],[6]])
>>> b
array([[5],
[6]])
>>> linalg.inv(A).dot(b) #slow
array([[-4. ],
[ 4.5]]
>>> A.dot(linalg.inv(A).dot(b))-b #check
array([[ 8.88178420e-16],
[ 2.66453526e-15]])
>>> np.linalg.solve(A,b) #fast
array([[-4. ],
[ 4.5]])
>>> A.dot(np.linalg.solve(A,b))-b #check
array([[ 0.],
[ 0.]])