numpy计算错误 [英] Numpy is calculating wrong
本文介绍了numpy计算错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在像这样的代码使用numpy
I am using numpy like this code
>>>import numpy as np
>>>a=np.arange(1,100000001).sum()
>>>a
987459712
我猜结果一定是这样的 5000000050000000
I guess the result must be some like 5000000050000000
我注意到直到五个数字,结果还是可以的. 有人知道发生了什么事吗?
I noticed that until five numbers the result is ok. Does someone knows what is happened?
致谢
推荐答案
Numpy在这里没有犯错.这种现象称为整数溢出.
Numpy is not doing a mistake here. This phenomenon is known as integer overflow.
x = np.arange(1,100000001)
print(x.sum()) # 987459712
print(x.dtype) # dtype('int32')
在arange
中用于给定输入的32位整数类型不能容纳5000000050000000.最多可以使用 2147483647 .
The 32 bit integer type used in arange
for the given input simply cannot hold 5000000050000000. At most it can take 2147483647.
如果显式使用较大的整数或浮点数据类型,则将获得预期的结果.
If you explicitly use a larger integer or floating point data type you get the expected result.
a = np.arange(1, 100000001, dtype='int64').sum()
print(a) # 5000000050000000
a = np.arange(1.0, 100000001.0).sum()
print(a) # 5000000050000000.0
这篇关于numpy计算错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文