-3

There is an error with Python. Here is the code:

print(np.sum(np.power(range(26), 6)))
print(np.sum(np.power(range(26), 7)))

which gives the following results:

998881325
792709145

How can the sum of (x to the power of 6) < sum of (x to the power of 7) !?!

EDIT


I'm on Python 3.7.3 and numpy 1.16.2.

MRT
  • 793
  • 7
  • 12

1 Answers1

3

You are generating integers that are larger than what your platform or default numpy int values can handle, so are overflowing your numbers.

25 to the seventh power requires 33 bits:

>>> (25 ** 7).bit_length()
33

Python's built-in integer type is unbounded, but numpy uses bounded, fixed size integers, and for your numpy setup, the default signed integer type is int32, so fails to fit this value.

I can reproduce the exact same output if I tell numpy to convert the output to int32:

>>> np.sum(np.power(range(26), 7)).astype(np.int32)
792709145

but because I have am running MacOS on a 64-bit CPU, numpy uses int64 as the default integer type and so produces the correct result:

>>> np.sum(np.power(range(26), 7))
22267545625
>>> np.sum(np.power(range(26), 7)).dtype
dtype('int64')

792709145 is the integer value represented by the bottom 31 bits:

>>> print(int(format(22267545625, 'b')[-31:], 2))
792709145

On Windows however, the default numpy integer type is int32 because even on 64-bit hardware Windows defines C long int as a 32-bit value.

You should tell numpy to create an array of int64 values here:

np.sum(np.power(np.arange(26, dtype=np.int64), 7))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    I am running on 64-bit OS as well, so I don't know why this would happen by default? – MRT Mar 21 '20 at 15:45
  • 1
    The default integer type for numpy on Windows is 32-bit, regardless of the Python installation or OS both being 64-bit. I was bitten by this (and, sadly, continue to be every so often): https://stackoverflow.com/questions/41705764/numpy-sum-giving-strange-results-on-large-arrays. By the view count, I'm not alone :) @MRT – roganjosh May 01 '20 at 10:32
  • @roganjosh ah, indeed, i found https://stackoverflow.com/questions/36278590/numpy-array-dtype-is-coming-as-int32-by-default-in-a-windows-10-64-bit-machine – Martijn Pieters May 02 '20 at 00:18
  • 1
    @MRT: just a heads-up: as roganjosh pointed out, the default int type on numpy on Windows is `int32`, because that's what the Windows API says is the size of a C long int. This differs from other OSes on 64-bits architectures, where long int is 64 bits. I've updated my answer accordingly. – Martijn Pieters May 02 '20 at 14:31