Python 中的不精确舍入

Imprecise Rounding in Python

是否有使用 32 位而不是 64 位进行 Python 舍入的简单方法?它的工作方式与 JavaScript 的 Math.fround 相同,但我 运行 脑子里想不出解决方案。

一种快速的方法是将数字分配给 ctypes.c_float 对象的值:

from ctypes import c_float

d = 1.2345678901234567890
f = c_float()
f.value = d
print(d) # 64-bit double
print(f.value) # 32-bit float

这输出:

1.2345678901234567
1.2345678806304932

与 JavaScript 中的 Math.fround 相比:

console.log(Math.fround(1.2345678901234567890))

尝试使用 numpy float32

np.float32(6.33333333333)

你应该阅读其他 question