UDF for linear transformation of numeric values

26 08 2008

Today I wrote a little UDF linearly transforms a value from a given scale, to an arbitrary scale with the specified range.

Say what?

Let’s say I have a test for which the maximum possible score is 25, and the minimum possible score is 5. I might want to rescale that score so that is has a minimum of 0 and a maximum of 10. This could be because I have to report the scores of many different test scores, each with their own minimum and maximum, and I want an easy way to compare these scores.  This UDF is a simple way to accomplish this. You can download the code here.

UDF

<cfscript>
/**
Linearly transforms a value from a scale with a given mininum and maximum,
to a new scale with given minimum and maximum
*
* @param value - Numeric: the value that must be rescaled.
* @param originalMin - Numeric: the minimum of the original, untransformed scale.
* @param originalMax - Numeric: the maximum of the original, untransformed scale.
* @param newMin - Numeric: the desired minimum for the new, transformed scale.
* @param newMax - Numeric: the desired maximum for the new, transformed scale.
* @return - Numeric: the linearly transformed value
* @author Martijn van der Woud (http://martijnvanderwoud.wordpress.com) at Orga-Toolkit (http://www.orga-toolkit.nl)
* @version 1, August 26, 2008
*/
function linearRescale(value, originalMin, originalMax, newMin, newMax) {
return arguments.newMin +
(arguments.newMax - arguments.newMin) *
(arguments.value - arguments.originalMin) /
(arguments.originalMax - arguments.originalMin);
}
<cfscript>

Example usage

<!--- the properties of the original scale --->
<cfset variables.originalMin = 5>
<cfset variables.originalMax = 25>
<!--- the (desired) properties of the new, transformed scale --->
<cfset variables.newMin = 0>
<cfset variables.newMax = 10>
<!--- The value that must be transformed --->
<cfset variables.value = 20>
<!--- calculate the rescaled value --->
<cfset variables.rescaledValue = linearRescale(
variables.value,
variables.originalMin,
variables.originalMax,
variables.newMin,
variables.newMax)>
<cfoutput>#rescaledValue#</cfoutput>