除以零时得到无穷大

NeP*_*UnE 7 python

是否可以将无穷大分配给除以的东西0而不是抛出它ZeroDivisionError

就像一个将无穷大赋给 的函数something/0

tim*_*geb 5

如果您只想要一个代表无穷大的浮点数,您可以发出float('inf')float('-inf')


标准Python浮点数和整数会给你一个ZeroDivisionError,但你可以使用numpy数据类型。

>>> import numpy as np
>>> np.float64(15)/0
inf
Run Code Online (Sandbox Code Playgroud)

没有numpy,写一个函数:

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')
Run Code Online (Sandbox Code Playgroud)