Useful utility functions – 0 of n
This is the first in what I’m sure will be a lengthy series of posts about utility functions I find myself needing time and time again. When I say utility function, I generally just mean a static function that does something useful (aka helper function), whose logic is often self-contained and unrelated to a specific class or component.
The first of these methods I never knew I was missing until I played around with Processing one weekend. The method in question is a mapping function taking a value in one range to a value in another range. Its signature is as follows:
map(value, low1, high1, low2, high2)
The Processing description of the method says
Re-maps a number from one range to another. In the example above, the number ‘25’ is converted from a value in the range 0..100 into a value that ranges from the left edge (0) to the right edge (width) of the screen.
Numbers outside the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful.
My Java implementation of map is as follows:
/** * @param value The incoming value to be converted * @param low1 Lower bound of the value's current range * @param high1 Upper bound of the value's current range * @param low2 Lower bound of the value's target range * @param high2 Upper bound of the value's target range */ public static final double map(double value, double low1, double high1, double low2, double high2) { double diff = value - low1; double proportion = diff / (high1 - low1); return lerp(low2, high2, proportion); } // Linearly interpolate between two values public static final double lerp(double value1, double value2, double amt) { return ((value2 - value1) * amt) + value1; }
Any time you’re converting from one range of numbers to another, this method will come in handy. You probably have code already to handle this on an ad hoc basis; I know I certainly did before seeing the method in Processing. Hopefully this is helpful to you.