Reputation: 5840
I have a value that i need to translate to a percentage given a certain set of rules.
VALUE=X
Where X can be anything starting from 0
If:
X > 200
the result of my function should be 100 (percent).
If:
X < 200 AND >= 100
the result should be between 100 and 50 (percent). Example: X=150 would be 75%
If:
X < 100 AND >= 80
the result should be between 50 and 25 (percent). Example: X=90 would be 37.5%
And if:
X < 80
the result should be between 25 and 0 (percent).
My approach in PHP would be something like
if($value > 200) return 100;
if($value > 100 && $value < 200) return ???;
... and so on.
Wherein ??? obviously stands for the formula i don't know how to set up.
Is there a way to do this in one single formula? And even if not - what is the mathematical approach to this problem?
I know it is very basic but it seems i skipped too many maths lessons in primary school.
Upvotes: 0
Views: 3202
Reputation: 81384
The function can be defined piecewisely:
Graphically, this is represented with four straight lines of different gradients. While there isn't a way to represent this function without separate pieces, implementing the above is quite easy.
In PHP, this function can be written as:
function f($x) {
if ($x >= 200)
return 100;
if ($x >= 100 && $x < 200)
return 50 + 50 * (($x - 100) / 100);
if ($x >= 80 && $x < 100)
return 25 + 25 * (($x - 80) / 20);
if ($x < 80)
return 25 * ($x / 80);
}
Upvotes: 5
Reputation: 239791
First, determine which range you should be in. Then:
So X from 100 to 200 gives a score from 100 to 50. The bottom of the range is 100; the size of the range is 100 (200 - 100), and the score goes from 100 at the beginning to 50 at the end, so the difference is -50. Therefore -50 * ($value - 100) / 100 + 100
would work, or simplifying, -0.5 * ($value - 100) + 100
or 150 - $value * 0.5
.
Working another example, from 80 to 100: the bottom of the range is 80, the size of the range is 20, and the score goes from 25 to 50 (difference: -25). You get -25 * ($value - 80) / 20 + 25
, which simplifies to -1.25 * ($value - 80) + 25
or 125 - $value * 1.25
Upvotes: 1