Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy is calculating wrong [duplicate]

Tags:

python

numpy

I am using numpy like this code

>>>import numpy as np
>>>a=np.arange(1,100000001).sum()
>>>a
987459712

I guess the result must be some like 5000000050000000

I noticed that until five numbers the result is ok. Does someone knows what is happened?

regards

like image 270
Horus Ricardo Junoy Avatar asked Apr 04 '17 13:04

Horus Ricardo Junoy


1 Answers

I suspect you are using Windows, where the data type of the result is a 32 bit integer (while for those using, say, Mac OS X or Linux, the data type is 64 bit). Note that 5000000050000000 % (2**32) = 987459712

Try using

a = np.arange(1, 100000001, dtype=np.int64).sum()

or

a = np.arange(1, 100000001).sum(dtype=np.int64)

P.S. Anyone not using Windows can reproduce the result as follows:

>>> np.arange(1, 100000001).sum(dtype=np.int32)
987459712
like image 157
Warren Weckesser Avatar answered Oct 07 '22 10:10

Warren Weckesser