奇怪的错误:ZeroDivisionError:浮点除以零 [英] Strange Error: ZeroDivisionError: float division by zero
问题描述
我发现了一种奇怪的行为,希望有人对此做出解释.我在做:
I found a strange behavior and hope someone has an explanation for it. I'm doing:
if len(list) > 1 and len(list2) > 1:
total = sum(list) + sum(list2)
result = percentage(sum(list), total)
def percentage(part, whole):
return float(part) / float(whole) *100
这两个列表是float和int值的混合.我偶尔会得到:
The two lists are a mix of float and int values. I sporadically get:
ZeroDivisionError: 浮点数除以零
ZeroDivisionError: float division by zero
这对我来说没有意义.有人知道发生了什么吗?
This doesn't makes sense to me. Does anyone have an idea what's happening?
推荐答案
如果打印出导致此错误的 part
和 whole
的值,则问题很明显发生.
The problem is obvious if you print out the values of part
and whole
that caused this error to occur.
解决方案是像这样处理任何零除错误
The solution is to handle any Division by Zero errors like so
try:
result = percentage(sum(list), total)
except ZeroDivisionError:
# Handle the error in whatever way makes sense for your application
或者,您可以在除以之前检查为零
Alternatively, you can check for zero before you divide
def percentage(part,whole):
if whole == 0:
if part == 0:
return float("nan")
return float("inf")
return float(part) / float(whole) *100
(感谢Joran Beasley和Max在数学上做到这一点正确)
(Thank you Joran Beasley and Max for making this mathematically correct)
这篇关于奇怪的错误:ZeroDivisionError:浮点除以零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!