What is the fastest algorithm to calculate percentage change between two doubles

3.6k Views Asked by At

I would like to know what is the best solution to find the percentage change of a double compared to another one. For example, I have a variable called 'current', I want to compare it to a variable called 'previous'. I need this for statistic purposes so that I can analyze the growth or the loss of value. I wrote my own algorithm, but it's very basic and it includes 2 if(s), which makes it too programming language dependent. Ideally I would like to find a one-line calculation.

double current = 10;
double previous = 20;
double result = 0.0;
// growth
if (current > previous)
{
  result = (100 / current) * previous;
}
// loss
if (current < previous)
{
  result = (100 / previous) * current;
}

Do you have any advice?

1

There are 1 best solutions below

0
On

If you're looking for the percentage loss/gain and 'compare current to previous' I would suggest that you want the denominator in your fraction to always be the previous value. This would make the value more consistent from a heuristic perspective, as it will always tell you the fraction relative to what you had, rather than changing behavior depending on whether you have loss or gain. Then you could with $\frac{\text{current}}{\text{previous}}\times 100$ for the percentage of 'previous' that 'current' is, or if you want the percentage change that would be $\frac{\text{current-previous}}{\text{previous}}\times100$.

This will give you a consistent interpretation of what the number means, which you don't get if you have that those if tests. Of course, if your doing some specific statistical analysis there could be much more to this story.