gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:04:00 26 4
gpt4 key购买 nike

我有一个 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。我需要保留数据的原始精度。

最佳答案

不可能将 64 位精度存储在 32 位值中。在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com