我有两个值(先前和当前),我想检查它们之间的变化(百分比):
(current/previous)*100
Run Code Online (Sandbox Code Playgroud)
但如果前一个值为0,我会得到除零,如果值不会改变,我得到100%.
Mat*_*att 17
def get_change(current, previous):
if current == previous:
return 100.0
try:
return (abs(current - previous) / previous) * 100.0
except ZeroDivisionError:
return 0
Run Code Online (Sandbox Code Playgroud)
def get_percentage_diff(previous, current):
try:
percentage = abs(previous - current)/max(previous, current) * 100
except ZeroDivisionError:
percentage = float('inf')
return percentage
Run Code Online (Sandbox Code Playgroud)
这是我发现的更好的方法。
仅涵盖100% 以下的差异。如果增加超过 100%,则此解决方案失败
您需要将change(current-previous)除以previous,而不仅仅是当前.所以,长话短说:
change_percent = ((float(current)-previous)/previous)*100
Run Code Online (Sandbox Code Playgroud)
请注意,如果previous是,0您无法计算百分比的变化(无论python实现如何)