Search code examples
pythonnumpysum

Unexpected return value of Numpy.sum() in my local Jupyter


When running the following code when N = 100000 I get -1724114088

Otherwise, I get the right answer when running it in web python editor.

Does my Jupter have any setting error?

def sq(N):
    return np.sum(np.arange(N)**2)

Solution

  • Try this:

    def sq(N):
        return np.sum(np.arange(N, dtype = np.int64)**2)
    

    The numbers in your example are too large for the np.int32 data type, which numpy uses by default. If you use np.int64 you can go up to N = 10000000