python3.10_python – 为什么10/3等于3.3333333333333335而不是… 332或..334?
这是因为它是最接近的(64位)浮点数可以达到10/3的“真值”.
我在这里使用cython(包装math.h nexttoward函数),因为我不知道任何内置函数:
%load_ext cython
%%cython
cdef extern from "" 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的值以及此值的上一个和下一个可表示的浮点数时,我得到:
>>> '{:.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
所以彼此可表示的浮点值是“更远”的.