I have a function that takes a specific number and a range, and re-scales it to the corresponding number in a different range.
/**
* @param int number The number to adjust.
* @param int oldMin The old minimum value.
* @param int oldMax The old maximum value.
* @param int newMin The new minimum value to convert to.
* @param int newMax The new maximium value to convert to.
*
* @returns int The original number converted to the new boundary.
*/
function convertValueToBoundary(number, oldMin, oldMax, newMin, newMax)
{
return (((number - oldMin) * (newMax - newMin)) / (oldMax - oldMin)) + newMin
}
Formula
newValue = (((oldValue - oldMinimum) * (newMaximum - newMinimum)) / (oldMaximum - oldMinimum)) + newMinimum
Example
For instance, given the number 5
within a range of 0-10
, we want to increase the numerical range to be between 0-100
instead.
convertValueToBoundary(5, 0, 10, 0, 100) // Output -> 50
Optimization & Improvements
Is this the optimal way to conduct this calculation? After a number of different attempts the above formula is the best I could come up with. Given a scenario where this needs to execute multiple times in rapid succession, it would be ideal to have this execute with the least amount of arithmetic operations required.
The conversion should be conducted without the use of any native language functions as I plan to use the same formula across different languages and platforms.