如何在python中检测算法溢出?

如何在python中检测算法溢出?,python,floating-point,Python,Floating Point,我正在处理python中的一个分析问题,在这个问题中,我必须处理大的浮点数,并对其执行一些操作。我的密码似乎介于两者之间;仔细观察,我发现有时一个简单的add操作会返回inf,这一定是溢出 >>> a = float(2**1022) + float(2**1023) >>> print a 1.348269851146737e+308 >>> a = float(2**1023) + float(2**1023) >>>

我正在处理python中的一个分析问题,在这个问题中,我必须处理大的
浮点数,并对其执行一些操作。我的密码似乎介于两者之间;仔细观察,我发现有时一个简单的add操作会返回
inf
,这一定是溢出

>>> a = float(2**1022) + float(2**1023)
>>> print a
1.348269851146737e+308
>>> a = float(2**1023) + float(2**1023)
>>> print a
inf
>>>

当进行浮点运算时,我们如何在python中检查
溢出
,因为它没有给出
溢出错误
而是默默地给出一个值
inf

我只能想象检查
如果abs(a)==float('inf'):raiseoverflowerror()

使用像GMPY这样的任意精度库,您就不必担心了。

免责声明:我维护gmpy2

该库支持任意精度(以减少溢出的发生)和捕获浮点事件的能力。下面是修改上下文以在发生溢出时自动引发异常的示例

>>> import gmpy2
>>> from gmpy2 import get_context,set_context, ieee, mpfr
>>> set_context(ieee(64))
>>> get_context()
context(precision=53, real_prec=Default, imag_prec=Default,
        round=RoundToNearest, real_round=Default, imag_round=Default,
        emax=1024, emin=-1073,
        subnormalize=True,
        trap_underflow=False, underflow=False,
        trap_overflow=False, overflow=False,
        trap_inexact=False, inexact=False,
        trap_invalid=False, invalid=False,
        trap_erange=False, erange=False,
        trap_divzero=False, divzero=False,
        trap_expbound=False,
        allow_complex=False)
>>> get_context().trap_overflow=True
>>> get_context()
context(precision=53, real_prec=Default, imag_prec=Default,
        round=RoundToNearest, real_round=Default, imag_round=Default,
        emax=1024, emin=-1073,
        subnormalize=True,
        trap_underflow=False, underflow=False,
        trap_overflow=True, overflow=False,
        trap_inexact=False, inexact=False,
        trap_invalid=False, invalid=False,
        trap_erange=False, erange=False,
        trap_divzero=False, divzero=False,
        trap_expbound=False,
        allow_complex=False)
>>> mpfr(2**1023) + mpfr(2**1023)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
gmpy2.OverflowResultError: 'mpfr' overflow in "addition"
>>> 
导入gmpy2 >>>从gmpy2导入获取上下文、设置上下文、ieee、mpfr >>>设置上下文(ieee(64)) >>>获取上下文() 上下文(精度=53,实数prec=Default,实数prec=Default, round=RoundToNearest,real\u round=Default,imag\u round=Default, emax=1024,emin=-1073, 欠规范化=真, 陷阱_下溢=假,下溢=假, 陷阱溢出=错误,溢出=错误, 陷阱不精确=错误,不精确=错误, 陷阱无效=错误,无效=错误, trap\u erange=False,erange=False, 陷阱_divzero=False,divzero=False, trap_expbound=False, 允许(复杂=错误) >>>获取上下文()。陷阱溢出=True >>>获取上下文() 上下文(精度=53,实数prec=Default,实数prec=Default, round=RoundToNearest,real\u round=Default,imag\u round=Default, emax=1024,emin=-1073, 欠规范化=真, 陷阱_下溢=假,下溢=假, 陷阱溢出=真,溢出=假, 陷阱不精确=错误,不精确=错误, 陷阱无效=错误,无效=错误, trap\u erange=False,erange=False, 陷阱_divzero=False,divzero=False, trap_expbound=False, 允许(复杂=错误) >>>mpfr(2**1023)+mpfr(2**1023) 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 gmpy2.OverflowResultError:“添加”中的“mpfr”溢出 >>>