Linear algrbra programs in Python Numpy
What is Linear algebra?
It is a
branch of mathematics which manipulates on matrices, vectors and linear equations.it
isa foundation for Science, Engineering, Machine Learning, Data Science and so on.
Key Terms:
Linear algebra deals with Scalars, Vectors, Matrices and
Linear Equations. Let us discuss each one of it.
- Scalars: It deals with Single numbers.Eg :-5,3,4.5.
- Vector: It is an ordered lists of numbers.
- Matrices : It is a rectangular array of numbers.
- Linear Algebra: Equations where variables have power 1.
Python:
import numpy as np1
def main():
try:
# Example
matrix
X = np1.array([[1,
1, 2],
[1,
3, 2],
[2,
1, 3]], dtype=float)
print("Matrix
X:\n", X)
# Finding
Matrix Rank
rank = np1.linalg.matrix_rank(X)
print("\nRank
of X:", rank)
# Determinant
of the matrix
det = np1.linalg.det(X)
print("Determinant
of X:", det)
# Trace of the
matrix
trace = np1.trace(X)
print("Trace
of X:", trace)
# Eigenvalues
and Eigenvectors Generation
eigenvalues, eigenvectors
= np1.linalg.eig(X)
print("\nEigenvalues:\n",
eigenvalues)
print("Eigenvectors:\n",
eigenvectors)
# Matrix
Inverse value (only if determinant != 0)
if det != 0:
inv_X = np1.linalg.inv(X)
print("\nInverse
of X:\n", inv_X)
else:
print("\nMatrix
X is singular; inverse does not exist.")
# Solving a
system of linear equations: Ax = b
b = np1.array([1,
2, 3], dtype=float)
print("\nVector
b:", b)
if det != 0:
x1 = np1.linalg.solve(X,
b)
print("Solution x for Xx = b:\n",
x1)
else:
print("Cannot
solve Xx = b because X is singular.")
except np1.linalg.LinAlgError
as e:
print("Linear
algebra error:", e)
except Exception as
e:
print("Unexpected
error:", e)
if __name__ == "__main__":
main()
Output:
Matrix X:
[[1. 1. 2.]
[1. 3. 2.]
[2. 1. 3.]]
Rank of X: 3
Determinant of X: -1.9999999999999998
Trace of X: 7.0
Eigenvalues:
[ 5.47089552+0.j
-0.21018413+0.j 1.73928861+0.j]
Eigenvectors:
[[-0.42336197+0.j
-0.83478852+0.j 0.12992958+0.j]
[-0.66731167+0.j
-0.07938673+0.j -0.86680154+0.j]
[-0.61274773+0.j 0.54481728+0.j 0.4814285 +0.j]]
Inverse of X:
[[-3.5000000e+00 5.0000000e-01
2.0000000e+00]
[-5.0000000e-01 5.0000000e-01
4.4408921e-17]
[ 2.5000000e+00
-5.0000000e-01 -1.0000000e+00]]
Vector b: [1. 2. 3.]
Solution x for Xx = b:
[ 3.5 0.5 -1.5]
These are the ways to implement the Linear algebra in python
using Numpy. Hope, you understood the concept. Keep Coding!!!
Comments
Post a Comment