5

I'm working on some linear algebra stuff, and simply can't figure out why numpy gives the following:

enter image description here

The result I got from mathematica, and by hand is

enter image description here

Edit: If you need the matrices:

test = [[19722145, -21016468, 51417377],
        [-185674670, 298847128, -428429486],
        [289326728, -516012704, 691212936]]

A = [[9, 4, 1], [2, 0, 8], [-8, 8, -8]]
jpp
  • 159,742
  • 34
  • 281
  • 339
n88b
  • 153
  • 2
  • 8

1 Answers1

3

As noted by @PaulPanzer, you need to use np.int64 dtype arrays. NumPy uses np.int32 for your input arrays on your platform / system configuration1 and does not check for integer overflow.

However, the result of your matrix multiplication includes integers which are too large to be stored in np.int32.

Since NumPy doesn't automatically upcast the input arrays to np.int64, you need to specify np.int64 explicitly, either when you define the array or via upcasting:

import numpy as np

test = np.array([[19722145, -21016468, 51417377],
                 [-185674670, 298847128, -428429486],
                 [289326728, -516012704, 691212936]],
                dtype=np.int64)

A = np.array([[9, 4, 1],
              [2, 0, 8],
              [-8, 8, -8]],
             dtype=np.int64)

res = np.dot(test, A)

print(res)

[[ -275872647   490227596  -559748615]
 [ 2354058114 -4170134568  5632538242]
 [-3957788344  6687010400 -9368478392]]

1 Here's another example. There's also been some discussion on platform-specific issues.

jpp
  • 159,742
  • 34
  • 281
  • 339
  • Thank you so much, such a noob mistake haha – n88b Jun 03 '18 at 21:43
  • Whether `numpy` uses `int32` or `int64` will depend on the OS and computer. Mine, a recent Linux on refurbished desktop uses `int64` as default. – hpaulj Jun 03 '18 at 22:20