简体   繁体   中英

Python Compiler - Using Decimal for Division of Zero?

I am currently creating a compiler and would also like to implement the division of zero. I noticed the decimal module in python and thought it could be useful. The code below shows what I am trying to get at. Is there anyway to split up the expression and check for the division of 0 for both negative and positive numbers? thanks in advance.

if input negative int/0 = -infin
if pos int/0 = infin
if 0/0 = null

ect.

The python documentation says the default behaviour is to raise an exception.

>>> import decimal
>>> D = decimal.Decimal
>>> a = D("12")
>>> b = D("0")
>>> a/b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/decimal.py", line 1350, in __truediv__
    return context._raise_error(DivisionByZero, 'x / 0', sign)
  File "/usr/lib/python3.4/decimal.py", line 4050, in _raise_error
    raise error(explanation)
decimal.DivisionByZero: x / 0
>>> 

But also, instead of raising an exception:

If this signal is not trapped, returns Infinity or -Infinity with the sign determined by the inputs to the calculation.

As of the zero by zero division, it is not mathematically defined, so I don't know what you may want to do with it. Python would return another exception:

>>> b/b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/decimal.py", line 1349, in __truediv__
    return context._raise_error(DivisionUndefined, '0 / 0')
  File "/usr/lib/python3.4/decimal.py", line 4050, in _raise_error
    raise error(explanation)
decimal.InvalidOperation: 0 / 0
>>>

and if the signal is not trapped, it returns NaN. (Might not be useful to know whether the operation was a zero divided by zero or not).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM