繁体   English   中英

如何检查两个值之间的变化(百分比)?

[英]How to check change between two values (in percent)?

我有两个值(以前的和当前的),我想检查它们之间的变化(百分比):

(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')

您需要将更改( current-previous )除previous ,而不仅仅是当前。 所以,长话短说:

change_percent = ((float(current)-previous)/previous)*100

请注意,如果previous0 ,则无法计算百分比的变化(无论 Python 实现如何)

要涵盖所有零的情况,您可以在语句中使用三元运算符

(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"

请记住,如果您之前的数字为零除以零是未定义的: https : //en.wikipedia.org/wiki/Division_by_zero

此外,您不应该使用分母的绝对值而不是分母。 这是一个例子:

先前值:-5

当前值:-4

| (-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

def get_percentage_diff(previous, current):
    try:
        percentage = abs(previous - current)/max(previous, current) * 100
    except ZeroDivisionError:
        percentage = float('inf')
    return percentage

这是我发现的更好的方法。

我用这个

  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

这是为了更正从网站获取公式的答案:

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)

Output:111.111% 差异

我猜最优化的方式是这样

def percentage_change(current,previous):
    if current and previous !=0:
       return round((current/previous)-1*100,2)

我的解决方案:

def find_difference(a, b):
    return ((abs(a - b)) / ((a + b) / 2)) * 100

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM