我有两个数值(之前的和当前的),我想检查它们之间的变化(以百分比表示):
(current/previous)*100
但如果先前的值为0,我会得到除以零的错误,并且如果值没有变化,我会得到100%。
def get_change(current, previous):
if current == previous:
return 100.0
try:
return (abs(current - previous) / previous) * 100.0
except ZeroDivisionError:
return 0
编辑:有些人评论说OP描述的是当前代码的问题,而不是要求这种行为,因此在这里举一个例子:“如果当前值等于以前的值,则没有变化。您应该返回0”。此外,如果以前的值为0,我已经使该方法返回Infinity,因为当原始值为0时,不存在真正的百分比变化。
def get_change(current, previous):
if current == previous:
return 0
try:
return (abs(current - previous) / previous) * 100.0
except ZeroDivisionError:
return float('inf')
return (abs(current - previous) / current ) * 100.0
? - ascendedcrow1
到2
值的变化为例,当前的响应是100
,如果一个值翻倍了,它改变了100%,这是有意义的。但如果我们使用当前
作为分母来实现它,它会给出一个50
的响应,但是双倍增长并不是一个50%的变化。 - Matt您需要将变化量(current-previous
)除以previous
,而不仅仅是当前值。简单来说:
change_percent = ((float(current)-previous)/previous)*100
请注意,如果previous
是0
,则无论Python的实现如何,都无法计算百分比变化。def get_percentage_diff(previous, current):
try:
percentage = abs(previous - current)/max(previous, current) * 100
except ZeroDivisionError:
percentage = float('inf')
return percentage
我发现了一个更好的方法。
只适用于不超过100%的差异。如果增加超过100%,则此解决方案将失败。
(current - previous) / previous * 100.0 if previous != 0 else float("inf") * abs(current) / current if current != 0 else 0.0
你应该除以前一个数的绝对值。 如果前一个数是负数且当前数也是负数,则如果在分母中不使用绝对值,将得到错误的结果。 例如,如果当前数字为-6,前一个数字为-5:
(-6 - (-5)) / -5 =
(-6 + 5) / -5 =
-1 / -5 = 20 %
这是明显错误的,因为在这种情况下百分比变化应该是负数-6 < -5
。所以请使用以下函数:
def percentage_change(current, previous):
if previous != 0 :
return float(current - previous) / abs(previous) * 100
else:
return "undefined"
| (-4 - (-5)) | / -5 =
| (-4 + 5) | / -5 =
|1| / -5 =
1 / -5 = -20%
这是错误的,因为 -4 > -5
正确:
(-4 - (-5)) / | -5 | =
(-4 + 5) / | -5 | =
1 / 5 = 20%
参考资料:https://www.calculatorsoup.com/calculators/algebra/percent-change-calculator.php
I use this
def pct_change(first, second):
diff = second - first
change = 0
try:
if diff > 0:
change = (diff / first) * 100
elif diff < 0:
diff = first - second
change = -((diff / first) * 100)
except ZeroDivisionError:
return float('inf')
return change
这是从this网站纠正答案取公式:
def get_percentage_diff(previous, current):
try:
percentage = abs(previous - current)/((previous + current)/2) * 100
except ZeroDivisionError:
percentage = float('inf')
return percentage
difference = get_percentage_diff(500,1750)
输出:111.111% 差异
我的解决方案:
def find_difference(a, b):
return ((abs(a - b)) / ((a + b) / 2)) * 100
def percentage_change(current,previous):
if current and previous !=0:
return round((current/previous)-1*100,2)
(current/previous)*100 - 100
。当然,这仍然不能让你除以零。 - TigerhawkT3current == previous
,这不是表示变化为0%,而不是100%吗?如果从100变为80,根据您的用例,这是20%还是80%? - krethika