import numpy
from numpy.linalg import pinv
m = 2
n = 3
A = numpy.random.randint(low=1, high=10, size=(m, n))
B = pinv(A)
if numpy.allclose(A, numpy.dot(A, numpy.dot(B, A))) and numpy.allclose(B, numpy.dot(B, numpy.dot(A, B))):
print("We could find pseudoinverse of A")
else:
print("We could not find pseudoinverse of A")
print("A: \n", A)
print("Pseudoinverse of A: \n", B)
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=(m, n) argument specifies that the created matrix will have m rows and n columns.
A = numpy.random.randint(low=1, high=10, size=(m, n))
Now, we are using the pinv() function from the numpy.linalg module to calculate the pseudoinverse of A.
B = pinv(A)
If B is indeed the pseudo inverse of A, then ABA = A and BAB = B. So, we are using the numpy.allclose() function to check the same.
if numpy.allclose(A, numpy.dot(A, numpy.dot(B, A))) and numpy.allclose(B, numpy.dot(B, numpy.dot(A, B))):
print("We could find pseudoinverse of A")
else:
print("We could not find pseudoinverse of A")
The output of the given program will be:
We could find pseudoinverse of A A: [[7 8 9] [5 7 6]] Pseudoinverse of A: [[ 0.14285714 -0.14285714] [-0.42857143 0.62857143] [ 0.38095238 -0.44761905]]






































0 Comments