for a subject I am implementing the Hill Cipher example from wikipedia using numpy. My code so far is below:
import numpy as np
msg = np.array([0, 2, 19]) # CAT
key = np.matrix([
[6, 24, 1],
[13, 16, 10],
[20, 17, 15]
])
ciphertext = np.mod(np.dot(key, msg), 26) # [5, 8, 13] # POH
# And here things go wrong
invKey = key.I
invKey2 = np.linalg.inv(key) # same as key.I
Until line 10 ("ciphertext") things work as they should. np.mod(np.dot(key, msg), 26) returns [15, 14, 7], as specified in the article. But when I try to do a matrix inverse I get drastically different results than I expected. The article suggests that the key matrix inverse should return this:
[[8, 21, 21],
[5, 8, 12],
[10, 21, 8]]
But instead this is returned:
[[ 0.15873016 -0.77777778 0.50793651]
[ 0.01133787 0.15873016 -0.10657596]
[-0.2244898 0.85714286 -0.48979592]]
Now, I can understand from various questions on this site that numpy.linalg.inv() has a problem with floating point precision. But these results are so different from the expected that there must be more going on right? I am new to numpy. Please help me understand what is going on here and how I can alleviate the problem, so the key matrix is inverted as the article specifies. Thank you for your time.