[英]How to calculate percentage within a value range in PHP
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 X可以是从0开始的任何东西
If: 如果:
X > 200
the result of my function should be 100 (percent). 我的功能的结果应该是100(百分比)。
If: 如果:
X < 200 AND >= 100
the result should be between 100 and 50 (percent). 结果应在100到50(百分比)之间。 Example: X=150 would be 75%
示例:X = 150将为75%
If: 如果:
X < 100 AND >= 80
the result should be between 50 and 25 (percent). 结果应在50到25(百分比)之间。 Example: X=90 would be 37.5%
示例:X = 90为37.5%
And if: 而如果:
X < 80
the result should be between 25 and 0 (percent). 结果应在25到0(百分比)之间。
My approach in PHP would be something like 我在PHP中的处理方式类似于
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. 我知道这是非常基础的,但看来我在小学时跳过了太多的数学课程。
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: 在PHP中,此函数可以编写为:
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);
}
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; 所以X从100到200给出的分数是100到50。范围的下限是100;范围的下限是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.
范围的大小是100(200-100),分数从开始的100到结束的50,所以差是-50。 Therefore
-50 * ($value - 100) / 100 + 100
would work, or simplifying, -0.5 * ($value - 100) + 100
or 150 - $value * 0.5
. 因此
-50 * ($value - 100) / 100 + 100
将起作用或简化为-0.5 * ($value - 100) + 100
或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). 另一个例子,从80到100:范围的底部是80,范围的大小是20,分数从25到50(差异:-25)。 You get
-25 * ($value - 80) / 20 + 25
, which simplifies to -1.25 * ($value - 80) + 25
or 125 - $value * 1.25
您得到
-25 * ($value - 80) / 20 + 25
,这简化为-1.25 * ($value - 80) + 25
或125 - $value * 1.25
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.