将数字范围映射到0到100

时间:2013-07-19 18:56:28

标签: php algorithm math

我有可能数字在+/- 6之间,包括0(即6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6 )来自我在PHP中的排名算法。

我希望返回0到100之间的数字,而不是返回+/- 6。相关性类似于:

100 = +6
.. 75 = +3
.. 50 = 0
.. 25 = -3
.. 0 = -6

考虑到排名算法的输出范围,我将如何在PHP中以编程方式实现此目的?我考虑过以下内容但不确定最佳方法:

function score_alg($x) {
  if ($x == '6')
    return 100;
  if ($x == '3')
    return 75;
  if ($x == '0')
    return 50;
  if ($x == '-3')
    return 25;
  if ($x == '-6')
    return 0;
}

7 个答案:

答案 0 :(得分:5)

这样可行:

function score_alg($x) {
  return round(($x+6)*(100/12));
}

答案 1 :(得分:2)

还有一个变种:

// Converts a range of numbers to a percentage scale
// $n       number to convert
// $lRange  lowest number of the range  [-6 default]
// $hRange  highest number in the range [6 default]
// $scale   percentage scale            [100 default]
function toPct($n, $lRange = -6, $hRange = 6, $scale = 100){
  // reversed high and low
  if ($lRange > $hRange){
    $lRange = $lRange + $hRange;
    $hRange = $lRange - $hRange;
    $lRange = $lRange - $hRange;
  }

  // input validation
  if ($n < $lRange || $n > $hRange) {
    trigger_error('$n does not fall within the supplied range', E_USER_ERROR);
    return FALSE;
  }

  // edge cases
  if ($n == $lRange) return 0;
  if ($n == $hRange) return $scale;

  // everything in between
  $range = $hRange - $lRange;
  if ($lRange < 0){
    $n += abs($lRange);
  }
  return ($n / $range) * $scale;
}

演示:

$lRange = -6; $hRange = 6;
for ($i = $lRange; $i <= $hRange; $i++){
  echo $i . ' = ' . toPct($i, $lRange, $hRange) . PHP_EOL;
}

输出:

-6 = 0
-5 = 8.3333333333333
-4 = 16.666666666667
-3 = 25
-2 = 33.333333333333
-1 = 41.666666666667
0  = 50
1  = 58.333333333333
2  = 66.666666666667
3  = 75
4  = 83.333333333333
5  = 91.666666666667
6  = 100

答案 2 :(得分:1)

你可以“伸展”范围:

function score_alg($x) {
    return round(($x + 6) * (100 / 12));
}

答案 3 :(得分:1)

你会做这样的事情:

function score_alg($x) {
  $val = ($x + 6)*(100/12); 
  return round($val);
}

<强>输出:

echo score_alg(6); //100
echo score_alg(3); //75
echo score_alg(0); //50
echo score_alg(-3); //25
echo score_alg(-6); //0

答案 4 :(得分:1)

我使用的小型通用范围功能:

function mapToRange($value, $in_min, $in_max, $out_min, $out_max ) {
   return round(($value - $in_min) * ($out_max - $out_min) / ($in_max - $in_min) + $out_min);
}

使用如下:

echo ( mapToRange( 0, -6, 6, 0, 100 )); // output is 50

答案 5 :(得分:0)

你可以这样做:

function score_alg($x) {
  return round(($x + 6)*(100/12)); 
}

答案 6 :(得分:0)

这里的大多数答案都是针对您的具体案例,只有一个解决方案涵盖任何案例,但是,这是不正确的。

以下是一个更快速的解决方案,应该全面运作。

/*
* $value // the value
* $min // minimum value of the range
* $max // maximum value of the range
*/
function toPercentage($value, $min, $max) {
  return ($value - $min) / ($max - $min) * 100;
};
相关问题