python - 从 float32 转换为 float 时如何保持精度?

标签 python numpy python-2.7 floating-point precision

我有一个 numpy.float32 对象,我想将其编码为 JSON。问题是,当我转换为 native python float 时,我会丢失该值的精度。

示例:

In [1]: import numpy as np
In [4]: np.float32(295.96).item()
Out[4]: 295.9599914550781

但是,如果我首先转换为字符串,然后转换为 float ,则精度将被保留。

In [3]: float(str(np.float32(295.96)))
Out[3]: 295.96

有没有一种方法可以保持我的精度而不必先遍历字符串?

为什么 str(np.float32(295.96)) 似乎保留了精度,但 np.float32(295.96).item() (或 float (np.float32(295.96))np.asscalar(np.float32(295.96))) 不是吗?

注意:我不能假设精度始终为 .01。我需要保留数据的原始精度。

最佳答案

不可能在 32 位值中存储 64 位精度。在 python 中,float 是 64 位(在 C 中称为 double)。作为演示,64 位 float 一切正常:

>>> d = 295.6; dn = np.float64(d)
>>> (d, dn)
(295.6, 295.95999999999998)  # numpy prints out more digits than python
>>> d == dn  # but these are still the same
True
>>> d - dn
0.0

但是如果您尝试使用 32 位,则会降低精度

>>> d = 295.96; fn = np.float32(d)
>>> (d, fn)
(295.96, 295.95999)
>>> d == fn
False
>>> d - fn
8.5449218545363692e-06

Why does str(np.float32(295.96)) seem to retain the precision

str(np.float32(295.96)) 看起来它保留了精度,因为为了方便起见,np.float32.__str__ 进行了舍入(以 10 为基数)。碰巧的是,当四舍五入时,它与您在代码中输入的文本完全匹配。因此,它具有完全相同的值。

关于python - 从 float32 转换为 float 时如何保持精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41967222/

相关文章:

python - 每当文本超过可视区域时,如何使文本自动向下滚动?

python - 以列表作为值的矩阵运算

python - 创造众多独特的事件

python - 单元测试中的设置部分似乎被忽略

python - 比较两个嵌套字典

python - 属性错误 : 'module' object has no attribute 'python_implementation' running pip

python - 使用 Python 在 Maya 中导入多个缓存文件

python - 将字典转换为 Python 数据框

python - 将列表转换为数据框/调整一行循环

python - 如何在两个坐标数组中找到相同的 x,y 坐标?