是否可以将说无穷大分配给除以 0
的东西而不是扔 ZeroDivisionError
?
就像将无穷大赋给 something/0
的函数一样.
最佳答案
如果你只想要一个代表无穷大的浮点数,你可以发出 float('inf')
或 float('-inf')
.
标准 Python 浮点数和整数将为您提供 ZeroDivisionError
,但您可以使用 numpy
数据类型。
>>> import numpy as np
>>> np.float64(15)/0
inf
无
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')
关于python - 除以零时得到无穷大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62264277/