9
votes

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

2
np a=np.arange(1,100000001).sum() - Horus Ricardo Junoy
edited your question to include proper formating for code (high the code parts on a new line and hit ctrl+k - MooingRawr
Cannot reproduce in python 2.7 with [email protected] or python3.5 and [email protected]. What are you using? - Jblasco
Also, changing the title of the question to something more precise would be a good idea... - Jblasco
Yes, if you do a=np.arange(1,100000001).sum() it gives 5000000050000000 as result - Sembei Norimaki

2 Answers

9
votes

Numpy is not doing a mistake here. This phenomenon is known as integer overflow.

x = np.arange(1,100000001)
print(x.sum())  # 987459712
print(x.dtype)  # dtype('int32')

The 32 bit integer type used in arange for the given input simply cannot hold 5000000050000000. At most it can take 2147483647.

If you explicitly use a larger integer or floating point data type you get the expected result.

a = np.arange(1, 100000001, dtype='int64').sum()
print(a)  # 5000000050000000

a = np.arange(1.0, 100000001.0).sum()
print(a)  # 5000000050000000.0
6
votes

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