Solving system of linear equations
let 2x1+3x2 +5x3= 10
3x1-2x2+x3=3
x1+5x2+7x3=8
the matrix representation is
Ax=b
where
A=[[ 2 , 3, 5],
[ 3, -2 ,1],
[ 1, 5 , 7 ]])
b=[10,3,8]
3x1-2x2+x3=3
x1+5x2+7x3=8
the matrix representation is
Ax=b
where
A=[[ 2 , 3, 5],
[ 3, -2 ,1],
[ 1, 5 , 7 ]])
b=[10,3,8]
The following is the python code to solve the problem using numpy
import numpy as np
A=np.array([[ 2 , 3, 5],
[ 3, -2 ,1],
[ 1, 5 , 7 ]])
b=np.array([10,3,8])
x=np.linalg.solve(A,b)
print(x)
o/p
[ 5.69230769 5.30769231 -3.46153846]Note: if the matrix is singular( determinant is 0), it will give error.The matrix A must also be square.
So this solve function need full rank square matrix.
solving system of equation using sympy
import sympy as sp
from sympy.interactive import printing
printing.init_printing(use_latex=True)
from sympy import Eq,solve_linear_system,Matrix
sp.Function('eq1')
sp.Function('eq2')
x,y=sp.symbols('x y')
eq1=Eq(2*x-y,-4)
eq2=Eq(3*x-y,-2)
display(eq1)
display(eq2)
systemofeqn=Matrix([[2,-1,-4],[3,-1,-2]])
display(systemofeqn)
display(solve_linear_system(systemofeqn,x,y))
o/p
2x−y=−43x−y=−2
[2−1−4
3−1−2]
{𝑥:2, 𝑦:8}
Approximate Solution in case of non square matrix using pseudo inverse
Approximate Solution in case of non square matrix using pseudo inverse
import numpy as np
A=np.array([[1,2,3],[4,5,6]])
b=np.array([2,3])
x=np.linalg.pinv(A).dot(b)
print(x)
o/p
[-0.55555556 0.11111111 0.77777778]
Comments
Post a Comment