Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading