python - 为什么 10/3 等于 3.3333333333333335 而不是 ...332 或 ..334?

标签 python

谁能具体解释一下为什么最后一位是 5 而不是 2 或 4? 知道一个 float 在二进制世界中肯定有一个不准确的地方,我无法确切地了解上面案例的结果是如何详细得出的。

最佳答案

这是因为它是(64 位)float 最接近 10/3 的“真实值”。

我在这里使用 cython(包装 math.h nexttoward 函数),因为我不知道任何内置函数:

%load_ext cython

%%cython
cdef extern from "<math.h>" nogil:
    # A function that get's the next representable float for the 
    # first argument in direction to the second argument.
    double nexttoward(double, long double)

def next_float_toward(double i, long double j):
    return nexttoward(i, j)

(或者正如@DSM 所指出的,您也可以使用 numpy.nextafter )

当我显示 10/3 的值以及该值的前一个和下一个可表示 float 时,我得到:

>>> '{:.50}'.format(10/3)
3.3333333333333334813630699500208720564842224121094

>>> '{:.50}'.format(next_float_toward(10/3., 0))
3.3333333333333330372738600999582558870315551757812

>>> '{:.50}'.format(next_float_toward(10/3., 10))
3.3333333333333339254522798000834882259368896484375

因此彼此可表示的浮点值“更”远。

关于python - 为什么 10/3 等于 3.3333333333333335 而不是 ...332 或 ..334?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41194923/

相关文章:

python - 从分割句子中查找整数和字符串

python - 对多个列进行分组并在组内排名

python - docker/matplotlib : RuntimeError: Invalid DISPLAY variable

python - 通过对自身执行计算从 1dim numpy 数组创建 numpy 矩阵?

python - 带有元组的二维 numpy 数组 : expanding into multiple arrays w/combinations of original tuples

python - 使用多处理/线程将 numpy 数组操作分解为 block

python - 如何使用固定列表或数组大小作为值的 defaultdict 或字典

python - 在 python 中解压枚举的 zip

python - Pandas to_sql() 更新数据库中的唯一值?

python - 如果随机游走在随机初始化值的范围内,则停止条件