gpt4 book ai didi

python - 除以零时得到无穷大

转载 作者:行者123 更新时间:2023-12-04 17:27:40 29 4
gpt4 key购买 nike

是否可以将说无穷大分配给除以 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com