python - 字符串和 int 格式中 float 的区别。为什么?

标签 python python-3.x precision floating-accuracy nanotime

我需要纳秒级的当前时间。 作为字符串 "%.9f" % float_time它是 1502872986.653693676。最后你可以看到76。 如果我尝试写成与 int int(float_time*10**9) 相同的时间,它将是 1502872986653693696 ,最后是 96 。为什么?哪种是获得 nano 格式的正确方法?

from time import time

float_time = time()
print("float_time:", float_time)
int_nano_time = int(float_time*10**9)
print("int_nano_time:", int_nano_time)
str_nano_time = "%.9f" % float_time
print("str_nano_time:", str_nano_time)

float_time: 1502872986.6536937

int_nano_time: 1502872986653693696

str_nano_time: 1502872986.653693676

解决方案:

time.monotonic()

float_time: 536596.296

int_nano_time: 536596296000000

str_nano_time: 536596.296000000

最佳答案

两者在约 15.7 个十进制数字的 IEEE754 double 范围内都是正确的。原因是十的倍数无法精确生成,因此虽然乘以 2 ** 10 是精确的,但乘以 5 ** 10 又会产生舍入误差,这就是为什么最后的数字不同。

'1502872986.653693675994873046875000000000'
>>> "%.30f" % (1502872986.653693676 * 10 ** 9)
'1502872986653693696.000000000000000000000000000000'

这两个 float 的十六进制表示法截然不同:

>>> (1502872986.653693676 * 10 ** 9).hex()
'0x1.4db4704d00617p+60'
>>> (1502872986.653693676).hex()
'0x1.6650166a9d61ep+30'

至于从 time() 调用返回的时间 - 计算机很可能有一个计时器,可以提供足够高精度的时间戳 any时间值将介于 time() 被调用和返回的确切时间之间:

>>> (time() - time()) * 10 ** 9
-715.2557373046875
>>> (time() - time()) * 10 ** 9
-953.67431640625
>>> (time() - time()) * 10 ** 9
-953.67431640625

您的错误为 20 纳秒,但在我的计算机上,从 time() 调用返回的 2 个连续时间戳之间的时间差为 700-100 纳秒。

关于python - 字符串和 int 格式中 float 的区别。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45709564/

相关文章:

python - 如何将添加字符串应用到数据框子集的列

python - 如何从 Python 中的 HTML 页面中提取 URL

python-3.x - 如何忽略functools中的参数。 lru_cache?

java - 不能对 Double.MAX_VALUE Java 使用减法运算符

java - 如何使用 BigDecimal 显示始终有 2 个小数点的数字?

Netbeans 中的 Python 引用外部模块

python - Eclipse+PyDev+GAE 内存缓存 "Undefined variable from import: get"

python - 如何使用 Python 在 Ubuntu 中创建自己的命令

python - 测量pyc和py文件之间的性能差异

linux - AIX 和 Linux 上的 Fortran 输出不正确