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

所以彼此可表示的浮点值是“更远”的.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值