将long int转换为float时,numpy失去精度

时间:2018-11-14 13:24:31

标签: python numpy

当转换为浮点类型时,似乎numpy对numpy.int64值失去了精度。

我的numpy版本是1.15.4,seemed to fix this error

这里是一个例子:

>>> value = 734625324872288246
>>> value_plus_1 = 734625324872288246 + 1
>>> items = [value, value_plus_1]
>>> value.bit_length()
60
>>> value_plus_1.bit_length()
60
>>> import numpy as np
>>> a = np.array(items, dtype = np.float128) # larger than needed for value
>>> a
array([7.34625325e+17, 7.34625325e+17], dtype=float128)
>>> a.astype(np.int64) # larger than needed for value
array([734625324872288256, 734625324872288256])
>>> np.__version__
'1.15.4'

如您所见,现在数组中的两个值都是相等的,这表明我认为精度在转换为float时发生了损失。

我的问题是;创建可以纠正而不会丢失精度的numpy数组时,我做错什么了吗?

2 个答案:

答案 0 :(得分:2)

numpy文档(https://docs.scipy.org/doc/numpy-1.15.0/user/basics.types.html)指出,float64的实现仅对尾数使用52位,对指数使用11位。这很可能不足以完全存储您的60位数字的精度。

答案 1 :(得分:1)

(这个问题几乎肯定是重复的,但是我今天的搜索能力很弱。)

只能用64位浮点数表示有限的数字。可以精确表示的数字之间的间距取决于数字的大小;您可以使用函数numpy.spacing(x)找到浮点数x的间距。您的情况是,734625324872872288246周围的浮点数的间距为128:

In [33]: x = float(734625324872288246)

In [34]: x
Out[34]: 7.346253248722883e+17

In [35]: np.spacing(x)
Out[35]: 128.0

整数值625625324872872288246不能完全表示为浮点数。通过将浮点型转换回整数可以看到这一点。您不会得到相同的值:

In [36]: int(x)
Out[36]: 734625324872288256

您可以准确地将734625324324872288256表示为浮点数,但下一个较低的可表示整数是734625324872288256-128 = 734625324872288288。

以下是有关浮点问题的强制性链接: