What is wrong with this matrix multiplication in python

In the below code (Jupiter notebook), output is given wrong, how to correct the code?

import numpy as np

A = [1,22,231,1540]

B = [[-1,1,0],[1,-1,1],[0,6,0],[0,6,0]]

C = [[113401201],[10649],[1]]

result = np.dot(np.dot(A, B),C)

print(result)

output

 [-1800609408]

The actual answer is

enter image description here

I want to find the error and correct it

>Solution :

You’re probably running this code on 32-bit platform (where integers are 32 bit):

A = np.array(A, dtype=np.int32)
B = np.array(B, dtype=np.int32)
C = np.array(C, dtype=np.int32)

result = np.dot(np.dot(A, B), C)

print(result)

Prints (incorrectly, because the value overflows):

[-1800609408]

To correct it, use 64-bit values:

A = np.array(A, dtype=np.int64)
B = np.array(B, dtype=np.int64)
C = np.array(C, dtype=np.int64)

result = np.dot(np.dot(A, B), C)

print(result)

Prints:

[2494357888]

Leave a Reply