Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate numbers from a range to another range

Example range 1 (minimum and maximum):

[40 ... 480]

Example numbers from range 1:

[42, 59.4, 78.18, 120.43, 416]

Example range 2:

[10 .. 140]

How can I translate the values of the numbers from range 1 to values within the second range? 42 should be equivalent to something between 10 and 11 in the new range.

I'm using PHP but this is more like a math problem.

I know how to align them to the second range:

$diff = $range[0] - $numbers[0];
foreach($numbers as $i => $number){
  $numbers[$i] = $number + $diff;
}

But that's it :(

like image 537
Alex Avatar asked Sep 27 '13 18:09

Alex


1 Answers

Do you mean something like this, which scales the values linearly to fit within the new range?

var transformRange = (value, r1, r2) => {
  var scale = (r2.max - r2.min) / (r1.max - r1.min)
  return (value - r1.min) * scale;
}

Sample usage:

transformRange(100, {max: 150, min: 50}, {max: 1, min: 0}); => 0.5
like image 71
Katniss Avatar answered Nov 13 '22 21:11

Katniss