How to get NaN when I divide by zero

后端 未结 5 660
北海茫月
北海茫月 2020-12-08 08:54

When I do floating point division in Python, if I divide by zero, I get an exception:

>>> 1.0/0.0
Traceback (most recent call last):
  File \"

        
5条回答
  •  情话喂你
    2020-12-08 09:42

    You could try using the 'decimal' module:

    >>> from decimal import *
    >>> setcontext(ExtendedContext)
    >>> inf = Decimal(1) / Decimal(0)
    >>> print(inf)
    Infinity
    >>> neginf = Decimal(-1) / Decimal(0)
    >>> print(neginf)
    -Infinity
    >>> print(neginf + inf)
    NaN
    >>> print(neginf * inf)
    -Infinity
    >>> print(dig / 0)
    Infinity
    

提交回复
热议问题