import numpy as np import time N = 2000 # Our matrices are NxN trials = 10 # We repeat the experiment this many times equal = True # True if we believe AB=C A = np.random.rand(N, N) # Random NxN matrix with elements independent and uniform in [0, 1] B = np.random.rand(N, N) # As in the previous line t1 = time.time() # Mark the beginning of time in seconds C = A.dot(B) # Compute C = A B t2 = time.time() # End of time print(f"Took {t2-t1} seconds to multiply the matrices") # How long it took to multiply AB D = C # Make a copy of matrix C D[N//2][N//2] += 1e-2 # We alter D in one place only by adding 0.01 somewhere near the "center" of the matrix t1 = time.time() # Mark the beginning of time in seconds for i in range(trials): # Repeat this "trials" many times x = np.random.randint(0, 2, size=N) # x is a random vector of length N with elements 0 or 1 y = B.dot(x) # y = Bx z = A.dot(y) # z = Ay zz = D.dot(x) #zz = Dx dist = np.linalg.norm(z-zz) # Norm of the difference of the two vectors Dx and ABx if dist>1e-6: # If the difference is large we view the vectors as different print(f"Not equal. Norm of difference is {dist}") # We print that we found the vectors different equal = False # Mark that we found a difference and stop the experiment break t2 = time.time() # End of time print(f"Took {t2-t1} seconds to check equality") # How long did it take us to check the equality AB=C if equal: print("Equal") # If we found AB=C we print this