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

You are not logged in.

## Post a reply

Write your message and submit
|
Options

## Topic review (newest first)

ryos
2005-08-17 11:22:04

I like it like this:

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

But everone has their own style.

MathsIsFun
2005-08-15 16:44:01

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?

ganesh
2005-08-15 16:04:53

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!

Luca
2005-08-15 14:38:05

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.

## Board footer

Powered by FluxBB