将两个 64 位数字相除并将结果存储在浮点数中而不丢失精度

Divide two 64-bit numbers and store the result in a float without losing precision

假设您有一个非常大的 64 位值以微秒为单位测量时间。我想将其转换为以秒为单位的浮点数,这意味着将时间值除以 1000000。在不丢失数据的情况下,您可以按什么顺序执行除法和转换?

如果我先执行除法,它仍然是一个整数,并且我丢失了测量的亚秒部分。如果我先将值转换为浮点数,则测量值会从 64 位截断为 24 位,结果不正确。

如果您同时执行这两个操作,编译器是否足够聪明,知道该怎么做?或者这需要手动将其分解成碎片吗?

我明白,到目前为止,我仍然可能会通过除法而失去最终浮点数的精度,这很好。我想避免由于执行转换的方式而造成的任何额外损失。

既然你提到了 24 位,我假设你正在使用 single precision floating point numbers (float). Use double precision and you will get a 53 bit mantissa. That should be enough for a number of microseconds, otherwise use long double 并且你将在 x86-64 上使用 gcc 获得 63 位尾数。