Dmitriy Platonov
Dmitriy Platonov

Reputation: 23

Python: negative numbers, when multiplying a matrix by a vector with numpy

A = numpy.matrix([[36, 34, 26],
        [18, 44,  1],
        [11, 31, 41]])

X1 = numpy.matrix([[46231154], [26619349], [37498603]])

Need multiplying a matrix by a vector. I tried:

>>>A*X1
   matrix([[ -750624208],
        [ 2040910731],
        [-1423782060]])
>>> numpy.dot(A,X1)
   matrix([[ -750624208],
        [ 2040910731],
        [-1423782060]])

Why negative numbers? It's ok with lower numbers, for example:

A = numpy.matrix([[36, 34, 26],
        [18, 44,  1],
        [11, 31, 41]])
X1 = numpy.matrix([[8], [6], [6]])

>>>A*X1
matrix([[58],
        [38],
        [40]])

Upvotes: 2

Views: 2229

Answers (1)

Robert T. McGibbon
Robert T. McGibbon

Reputation: 5277

I believe you're on a 32-bit system, and you're seeing an integer overflow. Try defining the matrix and vector with the keyword argument dtype=np.int64, and see if you get a more meaningful answer.

On my 64 bit machine, I have the following output

In [1]: import numpy

In [2]: A = numpy.matrix([[36, 34, 26],
   ...:         [18, 44,  1],
   ...:         [11, 31, 41]])

In [3]:

In [3]: X1 = numpy.matrix([[46231154], [26619349], [37498603]])

In [4]: A*X1
Out[4]:
matrix([[3544343088],
        [2040910731],
        [2871185236]])

Upvotes: 4

Related Questions