以尽可能小的数量增加 Python 浮点值 [英] Increment a Python floating point value by the smallest possible amount

查看:55
本文介绍了以尽可能小的数量增加 Python 浮点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:我使用浮点值作为字典键.

Background: I'm using floating point values as dictionary keys.

偶尔,非常(也许永远不会,但不一定永远不会),会发生碰撞.我想通过尽可能小地增加浮点值来解决这些问题.我该怎么做?

Occasionally, very occasionally (and perhaps never, but not certainly never), there will be collisions. I would like to resolve these by incrementing the floating point value by as small an amount as possible. How can I do this?

在 C 中,我会修改尾数来实现这一点,但我认为这在 Python 中是不可能的.

In C, I would twiddle the bits of the mantissa to achieve this, but I assume that isn't possible in Python.

推荐答案

Python 3.9 及更高版本

从 Python 3.9 开始,于 2020 年 10 月 5 日发布,您可以使用 math.nextafter 函数:

Python 3.9 and above

Starting with Python 3.9, released 2020-10-05, you can use the math.nextafter function:

math.nextafter(x, y)

math.nextafter(x, y)

返回 x 之后朝向 y 的下一个浮点值.

Return the next floating-point value after x towards y.

如果 x 等于 y,则返回 y.

If x is equal to y, return y.

示例:

  • math.nextafter(x, math.inf) 上升:向正无穷大.

math.nextafter(x, -math.inf) 下降:向负无穷大.

math.nextafter(x, 0.0) 趋向于零.

math.nextafter(x, math.copysign(math.inf, x)) 从零开始.

另见math.ulp().

这篇关于以尽可能小的数量增加 Python 浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆