Python sum()返回负值,因为总和对于32位整数而言太大 [英] Python sum() returns negative value because the sum is too large for 32bit integer

查看:124
本文介绍了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...

这篇关于Python sum()返回负值,因为总和对于32位整数而言太大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆