Skip to content

Matrix multiplication (dot) fails silently for large integers v1.3.0rc2 (Trac #1469) #2066

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
thouis opened this issue Oct 19, 2012 · 1 comment

Comments

@thouis
Copy link
Contributor

thouis commented Oct 19, 2012

Original ticket http://projects.scipy.org/numpy/ticket/1469 on 2010-04-30 by trac user gtpitt, assigned to unknown.

When multiplying 2 matrices with large integer values the following error was observed. Please note that no warning or error message was received. This is running in Eclipse Version: 3.4.1 Build id: M20080911-1700. Pydev v 1.4.6.2788.
version 1.3.0rc2
gm1 :
[[ 0 1]
[ 1 -157249]]

gm2 :
[[ 8762 -28349]
[-54857 177487]]

gm = dot(gm2,gm1) (note the order, gm2 is first)

[[ -28349 162893367]
[ 177487 -2139904344]]

correct answer :
[[ -28349 4457860663]
[ 177487 -27909708120]]

4457860663 (34 bits) :
100001001101101011000111000110111

@thouis
Copy link
Contributor Author

thouis commented Oct 19, 2012

@pv wrote on 2010-05-01

Your matrices are made of 32-bit integers,

>>> import numpy as np
>>> a = np.array([[0,1],[1,-157249]])
>>> b = np.array([[8762, -28349],[-54857,177487]])
>>> a.dtype
dtype('int32')

These are defined on the machine level so that on overflow, the result wraps around:

>>> np.int32(1000000) * np.int32(1000000)
-727379968

If you want floating-point results, you need to use floating point numbers in your matrices:

>>> a = a.astype(float)
>>> np.dot(b, a)
array([[ -2.83490000e+04,   4.45786066e+09],
       [  1.77487000e+05,  -2.79097081e+10]])

or an integer type large enough to contain your results

>>> a = a.astype(np.int64)
>>> np.dot(b, a)
array([[      -28349, 4457860663],
       [      177487, -27909708120]], dtype=int64)

@thouis thouis closed this as completed Oct 19, 2012
seberg pushed a commit to seberg/numpy that referenced this issue Oct 23, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant