How to get NaN when I divide by zero

后端 未结 5 662
北海茫月
北海茫月 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:32

    Method 1:

    try:
        value = a/b
    except ZeroDivisionError:
        value = float('Inf')
    

    Method 2:

    if b != 0:
        value = a / b
    else:
        value = float('Inf')
    

    But be aware that the value could as well be -Inf, so you should make a more distinctive test. Nevertheless, this above should give you the idea how to do it.

提交回复
热议问题