Discussion about math, puzzles, games and fun. Useful symbols: ÷ × ½ √ ∞ ≠ ≤ ≥ ≈ ⇒ ± ∈ Δ θ ∴ ∑ ∫ π -¹ ² ³ °

You are not logged in.

- Topics: Active | Unanswered

Pages: **1**

**Luca****Guest**

Hi, I'm a software developer currently working on a statistics program. I have a series of values per month, and for each month I have to calcultate the percent difference from the preceeding month. Example:

January = 50; February = 75

% difference between January and February = +50%

I calculate this as follows:

[(75 - 50)/50]*100

Everything works fine until get 2 consecutive months with a 0 value, example:

March = 0; April = 0

% difference between March and April:

[(0 - 0)/0]*100 => which of course is infinite and returns an error. But we all know that in fact the % difference between these 2 months is zero...unfortunately a computer doesn't understand this.

My question: is there another formula I can use to calculate the difference, that will not return an error when 2 consecutive values are zero?

Thank you very much if you can help me.

**ganesh****Moderator**- Registered: 2005-06-28
- Posts: 21,484

If the value of the current month is B and the previous month A,

[(B-A)/A]*100 is the right way of calculating the percentage increase, which you have done. Problem arises when the difference is 0 and both the values are 0. I don't think there is any mathematical solution, but if you could program in such a way that

the formula is applied only when the difference ≠ 0

and when the difference is zero, the percentage change is zero,

your problem could be solved!

It is no good to try to stop knowledge from going forward. Ignorance is never better than knowledge - Enrico Fermi.

Nothing is better than reading and gaining more and more knowledge - Stephen William Hawking.

Offline

**MathsIsFun****Administrator**- Registered: 2005-01-21
- Posts: 7,626

Yes, this comes under the heading of trapping exceptions, in this case the divide-by-zero exception.

You would have the same problem if one month was 0 and the next anything. For example 0 to 10: (10-0)/0

It is because you are asking "what is the **relative** change since last month" - how do you relate to a zero month?

So, you must have an "if (A == 0) { PctDiff=0 } else { PctDiff=((B-A)/A)*100 }" kind of code. (I just made PctDiff=0, but even better would be to print out an "N/A" or something to show that you know it is not possible to calculate the %)

BTW, what language are you writing it in?

"The physicists defer only to mathematicians, and the mathematicians defer only to God ..." - Leon M. Lederman

Offline

**ryos****Member**- Registered: 2005-08-04
- Posts: 394

I like it like this:

percentDiff = ( (A == 0) || (B - A == 0) ? 0 : ((B - A) / A) * 100) )

But everone has their own style.

El que pega primero pega dos veces.

Offline

Pages: **1**