gpt4 book ai didi

python - numpy.nextafter 递减而不是递增

转载 作者:太空狗 更新时间:2023-10-29 20:52:27 25 4
gpt4 key购买 nike

我遇到了一个奇怪的案例。我尝试了 Pyson 发布的三种解决方案中的一种:Increment a python floating point value by the smallest possible amount .当我到达这个 float 时,所有三个解决方案都显示出奇怪的行为:1.15898324042702949299155079643242061138153076171875。

假设我有以下代码:

import numpy as np
from __future__ import division

a = 1.15898324042702949299155079643242061138153076171875
b = 0
b = np.nextafter(a,1)
print a, b

出于某种原因,不是将 b 递增到尽可能小的数量,而是将其递减。这是为什么?

以下是我通过玩弄得到的一些快速结果:

In [12]: a = 1.15898324042702949299155079643242061138153076171875

In [13]: a
Out[13]: 1.1589832404270295

In [14]: numpy.nextafter(a,1)
Out[14]: 1.1589832404270293

In [15]: numpy.nextafter(a,-1)
Out[15]: 1.1589832404270293

最佳答案

来自文档(强调我的):

nextafter(x1, x2[, out])

Return the next representable floating-point value after x1 **in the direction
of x2 element-wise**.

第二个参数不是 +/-1 给出的方向,它是目标值。

In [12]: a = 1.15898324042702949299155079643242061138153076171875

In [13]: a
Out[13]: 1.1589832404270295

In [14]: numpy.nextafter(a, 0)
Out[14]: 1.1589832404270293

In [15]: numpy.nextafter(a, 1)
Out[15]: 1.1589832404270293

In [16]: numpy.nextafter(a, 1.16)
Out[16]: 1.1589832404270297

In [17]: numpy.nextafter(a, 2)
Out[17]: 1.1589832404270297

关于python - numpy.nextafter 递减而不是递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13300984/

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