79

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?

3
  • 4
    Is dividing by zero actually NaN or Inf? Commented Apr 4, 2012 at 13:13
  • 17
    @beerbajay: 0.0 / 0.0 —> nan, 1.0 / 0.0 —> inf, -1.0 / 0.0 —> -inf. Commented Apr 4, 2012 at 13:14
  • 1
    Actually very interesting would be to change the Python behavior so it really works for 1.0 / 0 without explicitly retyping everything or putting try-except everywhere. Commented Apr 4, 2012 at 13:30

5 Answers 5

82

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.

Sign up to request clarification or add additional context in comments.

5 Comments

This worked great. You can even pass numpy.float64 values to SWIG-wrapped C libraries without any problems.
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.
The first time you run this, it will throw an error.
@becko: It prints a warning, which is quite different from throwing an error. You can control warnings using the built-in warnings module.
@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.
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.

3 Comments

Oh! Somehow I thought this was a new question. Anyway, it's there as of version 3.5
@glglgl I've checked this and I get inf, -inf and ` ` anyone know why that might be the ZeroDivisionError is always raised?
Note: 0/0 == NaN; the result of a/b is +Inf or -Inf if a != 0 and b == 0
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 

Comments

-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

2 Comments

Better float('inf') instead of 'inf' - you'll get a float then, not a string...
Better except ZeroDivisionError, except alone also catches KeyboardInterrupt etc.
-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 

2 Comments

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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.