gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:53:21 35 4
gpt4 key购买 nike

谁能具体解释一下为什么最后一位是 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/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com