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: B = numpy.linalg.inv(A) print("Inverse of Matrix A: \n", B) except LinAlgError: print("The matrix A is not invertible")
Here, we are first creating a matrix A that contains random integers. We are using the function numpy.random.randint() for that purpose. 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.
Now, we are using the inv() function from the numpy.linalg module to calculate the inverse of the matrix A.
Please note that if the matrix A is not invertible, the inv() function will raise a LinAlgError. And if A is invertible, the program will print the inverse of the matrix A.
The output of the mentioned program will be like the following:
Matrix A: [[4 3 7] [5 1 2] [2 2 8]] Inverse of Matrix A: [[-0.11111111 0.27777778 0.02777778] [ 1. -0.5 -0.75 ] [-0.22222222 0.05555556 0.30555556]]






0 Comments