Opposite of rounding

68 Views Asked by At

Is there a simple formula to express the following "adversarial" rounding function?

$$f(x) = \begin{cases} \lfloor x \rfloor & \text{if } | x - \lfloor x \rfloor | \ge | x - \lceil x \rceil | \\ \lceil x \rceil & \text{otherwise} \end{cases}$$

The simplest I could come up with is the following, which involves 5 operations:

$$f(x) = \lfloor x \rfloor + \lfloor ( \lceil x \rceil - x ) \rceil$$

Behavior for a fractional part of 0.5 may be arbitrarily chosen.

2

There are 2 best solutions below

0
On

A solution to rounding to second-nearest integer with $5$ operations, but one fewer rounding: $$f(x) = \lfloor (2\times \lfloor x \rfloor + 1 - x)\rceil$$

0
On

If your intention is to say that when a number $x$ is strictly between two integers, it should map to the farther integer rather than the nearer integer, your first formula is nearly the most (if not the most) direct expression of that intention.

If you want to reduce the number of operations that must be performed in order to decide which way to "round" a number, you could write $$ f(x) = \begin{cases} \lfloor x \rfloor & \text{if $x \geq \lfloor x \rfloor + \frac12$}, \\ \lceil x \rceil & \text{otherwise}. \end{cases} $$

How to count operations can be tricky because the floor and ceiling functions are not ordinary arithmetic operations, and "round to nearest" might be implemented by an addition followed by a floor function. But this formula has (in sequence) one rounding-down, one addition, one comparison (resulting in true or false), one branch depending on the true or false value, then one more rounding (up or down, depending on the branch).

For exposition I think a definition with cases is superior to one that uses clever tricks to fold the cases into one case. For implementation in a computer program, there was a time when it was imperative to avoid branches wherever possible, but technology has a habit of changing.