Thursday, November 23, 2006

Rounding To The Nearest

Programming languages and spreadsheets usually have a function to round to the nearest integer. But the task of rounding to the nearest something else comes up every now and again. Rounding up to lowest higher multiple of n, rounding down to the highest lower multiple of n , rounding to the closest n....

Algorithm roundToNearest
-------------------------------------
1. Multiply the amount by the reciprocal of the rounding base (N) you want to round to.
number = number * (1 / roundingBase)

2. Round the result using the built-in function.
number = roundToInteger(number),
where roundToInteger is whatever rounding function you want to use.
In case there is no such function available, you can simulate it. roundUp = integerPart of (number + 1), roundDown = integerPart of (number - 1), roundToClosest= integerPart of (number + 0.5) etc.

3. Multiply the resulting amount by the rounding base itself.
number = number * roundingBase

4. The resulting number is the original number rounded to the nearest rounding base.
result = number

Example 1 - Rounding 123.68 (up) to the next highest multiple of 40
Step 1: 123.68*(1/40) = 3.092
Step 2: 3.092 + 1 = 4.092, integer part is 4. (Did integerCeiling(3.092) )
Step 3: 4 * 40 = 160
Result: 160 is the answer.

Example 2 - Rounding 46.27 to the closest 0.06
Step 1: 46.27 * (1/0.06) = 771.16666666666666666666666666667
Step 2: Integer part of 771.16666666666666666666666666667 + 0.03, 771
Step 3: 771 * 0.06 = 46.26
Result: 46.26 is the answer.

Generalization (Compulsory Philosophical Reflection)
Often, what we have with us may not be exactly what our tool requires or expects. Adjust, make do and un-adjust! More technically, transform whatever is incompatible into a compatible form, do the required operation, apply the exact reverse transform. This is a strategy that is often needed in problem solving and. generally. it works!

No comments: