Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get infinity when dividing by zero

Tags:

python

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.

like image 661
NePtUnE Avatar asked May 24 '26 16:05

NePtUnE


2 Answers

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')
like image 99
timgeb Avatar answered May 26 '26 06:05

timgeb


My solution::

from math import inf, nan, copysign

def fdiv(x,y):
    return x/y if y else (copysign(x*inf, x*y) if x else nan)

This gives you a correctly signed inf or NaN result if y is 0.0 or -0.0. Note 0/0 is undefined which is why this returns nan in that case, but you could also return a signed zero by replacing that with x*y. The copysign() needs the x*inf bit to handle the case when x==nan, because nan evaluates as True, and copysign(inf,nan) returns inf.

Note it's also possible to use exception handling instead of directly checking y. This benchmarks a minuscule bit faster for the typical case of y!=0, but heaps slower if y==0, so IMHO this is better.

However, one case when using exceptions is nicer is if you are mixing this with numpy/pandas/whatever types that handle the divide-by-zero case by themselves.

like image 22
Donovan Baarda Avatar answered May 26 '26 07:05

Donovan Baarda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!