Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

math

I have two values (previous and current) and I want to check change between them (in percent):

(current/previous)*100

But if the previous value is 0 I get Division By Zero, and if value will not change I get 100%.

like image 996
Nips Avatar asked Jun 18 '15 22:06

Nips


2 Answers

def get_change(current, previous):
    if current == previous:
        return 100.0
    try:
        return (abs(current - previous) / previous) * 100.0
    except ZeroDivisionError:
        return 0

Edit: some have commented that OP was describing a problem with the current code, not asking for this behavior, thus here is an example where, "if the current is equal to previous, there is no change. You should return 0". Also I've made the method return Infinity if the previous value was 0, as there can be no real percentage change when the original value is 0.

  def get_change(current, previous):
    if current == previous:
        return 0
    try:
        return (abs(current - previous) / previous) * 100.0
    except ZeroDivisionError:
        return float('inf')
like image 90
Matt Avatar answered Nov 17 '22 12:11

Matt


You need to divide the change (current-previous) by the previous, not just the current. So, to make a long story short:

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

Note that if previous is 0 you cannot calculate the change in percentage (regardless of the python implementation)

like image 13
Mureinik Avatar answered Nov 17 '22 12:11

Mureinik