Moder New
Moder New

Reputation: 558

Numpy giving weird results while multiplying matrices

So I've two matrices:

A = np.array([[93478902,  389555660,  163056852, 208537174],
              [256421362, 1068627076, 447283132, 572058098],
              [438743250, 1828454948, 765313074, 978809440]])

B = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 12, 5],
              [10, 92, 23, 43]])

I multiply them using numpy function A.dot(B).
Although the expected result (as I fastly calculated) is something like this one:

[[5594140610, 23340280292, 9760363552, 12493632310]
 [15345685910, 64026781516, 26774387456, 34272361778]
 [26256930056, 109551815408, 45811788394, 58641073978]]

Numpy is 100% sure that it should be like this:

[[ 1299173314  1865443812  1170428960  -391269578]
 [-1834183274  -397727924  1004583680   -87376590]
 [  487126280 -2117334288 -1432851862 -1488468166]]

And I have no idea where I am making a mistake, and how on the earth it gets a lower than 0 number from the multiplication of greater than 0 numbers? Can anyone help with this?

Upvotes: 1

Views: 559

Answers (2)

ddejohn
ddejohn

Reputation: 8960

Looks like overflow to me. Changing to dtype='int64' seems solves the problem:

>>> A = np.array([[93478902,  389555660,  163056852, 208537174],
...               [256421362, 1068627076, 447283132, 572058098],
...               [438743250, 1828454948, 765313074, 978809440]], dtype='int64')
>>>
>>> B = np.array([[1, 2, 3, 4],
                  [5, 6, 7, 8],
                  [9, 10, 12, 5],
                  [10, 92, 23, 43]])
>>> A.dot(B)
array([[  5594140610,  23340280292,   9760363552,  13272743630],
       [ 15345685910,  64026781516,  26774387456,  36409615930],
       [ 26256930056, 109551815408,  45811788394,  62297983874]],
      dtype=int64)

Upvotes: 3

xkudsraw
xkudsraw

Reputation: 179

Are you sure that you are really storing those matrices in the variables? The fact that some matrix elements have a minus sign implies that there should be some negative elements in A or B

Upvotes: 1

Related Questions