Thursday, July 1, 2010

Rounding

Rounding a number to the nearest power of 10 is easy. Round up if the end is 50 or above, down if 49.9... or below. But what happens if you need to round to the nearest 5, or the nearest 45, or the nearest multiple of 2π?

Then use this simple formula, constructed during a sleepless night by me. It'll round any number x to the nearest multiple of n.

n int ((x/n) + 0.5)  (Where int(z) is the greatest integer less than z, also called the floor function; it's available on most graphing calculators and in most programming languages.)

It works for any n>0.

For complex numbers, apply separately to the real and imaginary components.

No comments: