Python sum()返回负值,因为总和对于32位整数而言太大

问题描述:

x = [1, 2, 3, ... ]
y = sum(x)

x的总和为2165496761,该值大于32位整数的限制 因此sum(x)返回-2129470535.

The sum of x is 2165496761, which is larger than the limit of 32bit integer So sum(x) returns -2129470535.

如何通过将其转换为长整数来获取正确的值?

How can I get the correct value by converting it to long integer?

这是我的导入列表:

import math, csv, sys, re, time, datetime, pickle, os, gzip
from numpy import *

获得此无效值的原因是您在int32上使用了np.sum.没有什么能阻止您不是使用np.int32而是np.int64np.int128 dtype来表示数据.例如,您可以使用

The reason why you get this invalid value is that you're using np.sum on a int32. Nothing prevents you from not using a np.int32 but a np.int64 or np.int128 dtype to represent your data. You could for example just use

x.view(np.int64).sum()

在旁注中,请确保您从不使用from numpy import *.这是一种可怕的习惯,也是您必须尽快摆脱的习惯.使用from ... import *时,您可能会覆盖一些Python内置函数,这使得调试非常困难.典型示例是您覆盖summax ...

On a side note, please make sure that you never use from numpy import *. It's a terrible practice and a habit you must get rid of as soon as possible. When you use the from ... import *, you might be overwriting some Python built-ins which makes it very difficult to debug. Typical example, your overwriting of functions like sum or max...