Reputation: 909
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
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
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
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
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