Mathematical Functions

User Contributed Notes

Hayley Watson 30-Jan-2013 04:47
Provides a function to rescale numbers so that the range [a,b] fits into the range [c,d].

<?php
function rescale($ab, $cd)
{
    list(
$a, $b) = $ab;
    list(
$c, $d) = $cd;
    if(
$a == $b)
    {
       
trigger_error("Invalid scale", E_USER_WARNING);
        return
false;
    }
   
$o = ($b * $c - $a * $d) / ($b - $a);
   
$s = ($d - $c) / ($b - $a);
    return function(
$x)use($o, $s)
    {
        return
$s * $x + $o;
    };
}

$fahr2celsius = rescale([32, 212], [0, 100]);
echo 
$fahr2celsius(98.6); // 37°C

?>