加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python是否具有java.lang.Math.nextUp的等价物?

发布时间:2020-12-16 22:19:35 所属栏目:Python 来源:网络整理
导读:参见英文答案 Increment a python floating point value by the smallest possible amount????????????????????????????????????14个 我有一个Python浮点数,我希望浮点数大于和小于1 ULP. 在Java中,我将使用 Math.nextUp(x) 和 Math.nextAfter(x,Double.NEGA

参见英文答案 > Increment a python floating point value by the smallest possible amount????????????????????????????????????14个
我有一个Python浮点数,我希望浮点数大于和小于1 ULP.

在Java中,我将使用Math.nextUp(x)Math.nextAfter(x,Double.NEGATIVE_INFINITY)执行此操作.

有没有办法在Python中执行此操作?我想过用math.frexp and math.ldexp自己实现它,但据我所知Python并没有指定浮点类型的大小.

最佳答案
你可以看一下Decimal.next_plus()/Decimal.next_minus()是如何实现的:

>>> from decimal import Decimal as D
>>> d = D.from_float(123456.78901234567890)
>>> d
Decimal('123456.789012345674564130604267120361328125')
>>> d.next_plus()
Decimal('123456.7890123456745641306043')
>>> d.next_minus()
Decimal('123456.7890123456745641306042')
>>> d.next_toward(D('-inf'))
Decimal('123456.7890123456745641306042')

确保decimal context具有您需要的值:

>>> from decimal import getcontext
>>> getcontext()
Context(prec=28,rounding=ROUND_HALF_EVEN,Emin=-999999999,Emax=999999999,capitals=1,flags=[],traps=[InvalidOperation,DivisionByZero,Overflow])

备择方案:

>使用ctypes调用C99 nextafter()

>>> import ctypes
>>> nextafter = ctypes.CDLL(None).nextafter
>>> nextafter.argtypes = ctypes.c_double,ctypes.c_double
>>> nextafter.restype = ctypes.c_double
>>> nextafter(4,float('+inf'))
4.000000000000001
>>> _.as_integer_ratio()
(4503599627370497,1125899906842624)

使用numpy:

>>> import numpy
>>> numpy.nextafter(4,float('+inf'))
4.0000000000000009
>>> _.as_integer_ratio()
(4503599627370497,1125899906842624)

尽管repr()不同,但结果是一样的.
>如果我们忽略边缘情况,那么@S.Lott answer的简单frexp / ldexp解决方案可以工作:

>>> import math,sys
>>> m,e = math.frexp(4.0)
>>> math.ldexp(2 * m + sys.float_info.epsilon,e - 1)
4.000000000000001
>>> _.as_integer_ratio()
(4503599627370497,1125899906842624)

> pure Python next_after(x,y) implementation by @Mark Dickinson考虑边缘情况.在这种情况下结果是相同的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读