NePtUnE
NePtUnE

Reputation: 909

Get infinity when dividing by zero

Is it possible to assign say infinity to something divided by 0 instead of it throwing ZeroDivisionError?

Like a function that assigns infinity to something/0.

Upvotes: 9

Views: 8480

Answers (4)

timgeb
timgeb

Reputation: 78750

If you just want a float that represents infinity, you can issue float('inf') or float('-inf').


Standard Python floats and ints will give you a ZeroDivisionError, but you can use numpy datatypes.

>>> import numpy as np
>>> np.float64(15)/0
inf

Without numpy, write a function:

def my_div(dividend, divisor):
    try:
        return dividend/divisor
    except ZeroDivisionError:
        if dividend == 0:
            raise ValueError('0/0 is undefined')
            # instead of raising an error, an alternative
            # is to return float('nan') as the result of 0/0

        if dividend > 0:
            return float('inf')
        else:
            return float('-inf')

Upvotes: 7

user8563312
user8563312

Reputation:

As mentioned before, you can use math.inf from math module.

You can catch a ZeroDivision error like this:

from math import inf

try:
    x = 5/0
except ZeroDivisionError:
    x = inf

Upvotes: 0

Chris Doyle
Chris Doyle

Reputation: 12085

you can either use python try except blocks or you can check the value of the divisor first and use an else case.

from math import inf
a = 5
b = 0
try:
    x = a / b
except ZeroDivisionError as zde:
    x = inf

if b:
    y = a / b
else:
    y = inf


print(x)
print(y)

OUTPUT

inf
inf

Upvotes: 0

Jose Henrique Roveda
Jose Henrique Roveda

Reputation: 180

You can achieve this using the numpy.float64().

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

This will not trow an error, but a warning. You can control warnings using the built-in warnings module

Upvotes: 0

Related Questions