[英]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
請注意,如果previous
是0
,則無法計算百分比的變化(無論 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.