77

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 "<stdin>", line 1, in <module>
ZeroDivisionError: float division

I'd really like to get NaN or Inf instead (because the NaN or Inf will propagate through the rest of my calculation correctly and not kill my program).

How can I do this?

Ken Bloom
  • 57,498
  • 14
  • 111
  • 168

5 Answers5

80

The easiest way to get this behaviour is to use numpy.float64 instead of Python default float type:

>>> import numpy
>>> numpy.float64(1.0) / 0.0
inf

Of course this requires NumPy. You can use numpy.seterr() to fine-tune the error handling.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 1
    This worked great. You can even pass `numpy.float64` values to SWIG-wrapped C libraries without any problems. – Ken Bloom Apr 04 '12 at 20:23
  • 20
    What's the point of even having `float('inf')` and `float('nan')` built in to Python if you have to use a 3rd-party library to get the expected behaviour? i.e., it seems like typing `float('inf')` explicitly is the only time I can actually count on seeing an 'inf' result returned by Python. – Brandin Jan 18 '16 at 14:18
  • The first time you run this, it will throw an error. – a06e Nov 24 '17 at 13:40
  • 3
    @becko: It prints a warning, which is quite different from throwing an error. You can control warnings using the built-in `warnings` module. – Sven Marnach Nov 24 '17 at 17:58
  • @Brandin E.g. `1e200 * 1e200` results in `inf`. But I agree, I would also like to either have IEEE 754 behavior all-round or no `inf` and `nan` at all. – Feuermurmel Apr 26 '20 at 09:47
28

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.

Augustin
  • 2,444
  • 23
  • 24
glglgl
  • 89,107
  • 13
  • 149
  • 217
10

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
Spacedman
  • 92,590
  • 12
  • 140
  • 224
-6

If i understand your problem properly then this should be the solution:

try:
   1.0/0.0
except:    
   return 'inf'

you can modified it according to various python exception handling method available

Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
-6

I used a wrapper function in a python program of mine for a simple division that was returning ZeroDivisionError when the sensors I was using weren't plugged in. It simply returns 0 (zero), which in real-world terms is what I wanted. Probably gets messy with more variables, however...

def calculation(a, b):
    if a == 0:
        return 0
    elif b == 0:
        return 0
    else:
        return a/b
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
  • 1
    Sorry, I forgot to revise this for what was being asked, but all you have to do is change the zero's to "NaN" I believe. – Colin MacRae Jul 15 '15 at 15:17
  • This is not a general solution. E.g. I would not expect a / 0.0 to give 0, nor would I expect it to give NaN. – Brandin Jan 18 '16 at 14:55