import numpy
from numpy.linalg import LinAlgError
n = 3
A = numpy.random.randint(low=1, high=10, size=(n, n))
print("Matrix A: \n", A)
try:
Q, R = numpy.linalg.qr(A)
print("The Orthogonal Matrix Q: \n", Q)
print("The Upper Triangular Matrix R: \n", R)
except LinAlgError:
print("The QR Decomposition of The Matrix A Failed")
R_inverse = numpy.linalg.inv(R)
Q_transpose = numpy.transpose(Q)
A_inverse = numpy.matmul(R_inverse, Q_transpose)
try:
if numpy.allclose(A_inverse, numpy.linalg.inv(A)):
print("The inverse of A: \n", A_inverse)
except LinAlgError:
print("The matrix A is not invertible")
Here, A is a 3×3 square matrix that contains random integers. We are using the numpy.randopm.randint() function for generating random integers. The generated random integers will be within the range [low, high). And the size=(n, n) argument specifies that the created matrix will have n rows and n columns.
We are using the function numpy.linalg.qr() to perform QR decomposition of the matrix A. If the QR decomposition fails, the function will raise a LinAlgError. Otherwise, we will get one orthogonal matrix Q and one upper triangular matrix R.
Now, we can calculate R-1QT to get the inverse of the matrix A.
R_inverse = numpy.linalg.inv(R)
Q_transpose = numpy.transpose(Q)
A_inverse = numpy.matmul(R_inverse, Q_transpose)
try:
if numpy.allclose(A_inverse, numpy.linalg.inv(A)):
print("The inverse of A: \n", A_inverse)
except LinAlgError:
print("The matrix A is not invertible")
Here, we are using the numpy.allclose() function to check whether R-1QT is indeed equal to the inverse of the matrix A.
The output of the given program will be:
Matrix A: [[6 1 9] [9 6 4] [9 3 7]] The Orthogonal Matrix Q: [[-0.42640143 0.58693919 -0.6882472 ] [-0.63960215 -0.73367398 -0.22941573] [-0.63960215 0.34238119 0.6882472 ]] The Upper Triangular Matrix R: [[-14.07124728 -6.18282077 -10.87323653] [ 0. -2.78796113 4.74442508] [ 0. 0. -2.29415734]] The inverse of A: [[-0.33333333 -0.22222222 0.55555556] [ 0.3 0.43333333 -0.63333333] [ 0.3 0.1 -0.3 ]]








































0 Comments