JUJU Chen
JUJU Chen

Reputation: 3

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)

Upvotes: 0

Views: 31

Answers (1)

markuscosinus
markuscosinus

Reputation: 2267

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

Upvotes: 1

Related Questions