python-3.x - 如何安全地将 float64 舍入并固定到 int64?

标签 python-3.x numpy floating-point integer-overflow

这个问题是关于 python/numpy 的,但它也可能适用于其他语言。

如何改进以下代码以将大的浮点值安全地限制在 转换期间的最大 int64 值? (理想情况下,它应该仍然有效。)

import numpy as np

def int64_from_clipped_float64(x, dtype=np.int64):
  x = np.round(x)
  x = np.clip(x, np.iinfo(dtype).min, np.iinfo(dtype).max)
  # The problem is that np.iinfo(dtype).max is imprecisely approximated as a
  # float64, and the approximation leads to overflow in the conversion.
  return x.astype(dtype)

for x in [-3.6, 0.4, 1.7, 1e18, 1e25]:
  x = np.array(x, dtype=np.float64)
  print(f'x = {x:<10}  result = {int64_from_clipped_float64(x)}')

# x = -3.6        result = -4
# x = 0.4         result = 0
# x = 1.7         result = 2
# x = 1e+18       result = 1000000000000000000
# x = 1e+25       result = -9223372036854775808

最佳答案

问题是最大的 np.int64 是 263 - 1,它不能用 float 表示。同样的问题不会发生在另一端,因为 -263 是完全可以表示的。

浮点空间(用于检测)和整数空间(用于校正)中的裁剪部分也是如此:

def int64_from_clipped_float64(x, dtype=np.int64):
    assert x.dtype == np.float64

    limits = np.iinfo(dtype)
    too_small = x <= np.float64(limits.min)
    too_large = x >= np.float64(limits.max)
    ix = x.astype(dtype)
    ix[too_small] = limits.min
    ix[too_large] = limits.max
    return ix

关于python-3.x - 如何安全地将 float64 舍入并固定到 int64?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66297767/

相关文章:

python - 如何使用基于Python中列中先前值的函数创建列

python - Moviepy 无法识别调整大小功能

linux - pip安装报错python3 linux

python - 如何过滤数据框以便在特定时间每天发生一次

python - 信号发生器特定噪声调制

C# NotFiniteNumberException 不起作用

python - Pandas 从列中删除值

python - 如何沿矩阵轴执行滚动求和?

java - 将 float 格式化为最多 N 个小数位

c++ - 将 float 数组与 int 数组进行比较