taocp

This site has no text of the book. Keep your own copy of TAOCP next to it. See what is checked.

Exercise · Volume 1 · 1.2.4-5

Exercise 1.2.4-5

proved in Lean solution written

Rating16
KindK3, find a value: compute a number, a set or a closed form from the written solution
SectionSection 1.2.4 of Volume 1. Companion chapter: Integer functions and elementary number theory

The task

Find one formula that rounds a positive real xx to the nearest integer, with a half going up, and say what the formula does for negative xx.

The exact wording is in your copy of the book.

Hints

Open one hint at a time. Try the exercise again after each.

Hint 1

Write x=⌊x⌋+fx = \lfloor x \rfloor + f with f=x mod 1f = x \bmod 1.

Hint 2

Add 12\tfrac12 to xx before you take a floor.

Solution

Show the solution

The formula is ⌊x+12⌋\lfloor x + \tfrac12 \rfloor. Write x=⌊x⌋+fx = \lfloor x \rfloor + f with 0≤f<10 \le f < 1. Then x+12=⌊x⌋+(f+12)x + \tfrac12 = \lfloor x \rfloor + (f + \tfrac12), and ⌊x⌋\lfloor x \rfloor is an integer, so ⌊x+12⌋=⌊x⌋+⌊f+12⌋\lfloor x + \tfrac12 \rfloor = \lfloor x \rfloor + \lfloor f + \tfrac12 \rfloor.

If f<12f < \tfrac12, then 0≤f+12<10 \le f + \tfrac12 < 1 and the last floor is 00. The result is ⌊x⌋\lfloor x \rfloor.

If f≥12f \ge \tfrac12, then 1≤f+12<321 \le f + \tfrac12 < \tfrac32 and the last floor is 11. The result is ⌊x⌋+1\lfloor x \rfloor + 1. In this case f>0f > 0, so xx is not an integer and ⌈x⌉=⌊x⌋+1\lceil x \rceil = \lfloor x \rfloor + 1. The result is ⌈x⌉\lceil x \rceil.

This is the required rule. The calculation did not use the sign of xx, so the formula is valid for negative xx too, and it still gives an integer nearest to xx. The only difference is the treatment of the halves: x=−2.5x = -2.5 has f=0.5f = 0.5 and the formula gives −2-2, which is the half rounded up toward +∞+\infty, not away from zero. A rounding that is symmetric about zero is sign⁡(x)⌊∣x∣+12⌋\operatorname{sign}(x)\lfloor |x| + \tfrac12 \rfloor. The formula ⌈x−12⌉\lceil x - \tfrac12 \rceil rounds every half down.

Check

For x=2.4x = 2.4 and 2.52.5 and 2.62.6 the formula gives 22, 33, 33. For x=−2.4x = -2.4, −2.5-2.5, −2.6-2.6 it gives −2-2, −2-2, −3-3. A computer run with exact fractions agrees for x=k/10x = k/10 with 1≤k≤991 \le k \le 99.

Remarks

Rounding the half to even is the rule of many floating-point units, to avoid a bias. The formula here has a bias of +12+\tfrac12 per tie. See Section 4.2.2 for rounding in floating-point arithmetic.

This solution is checked, and a person has not reviewed it yet. The source.

In Lean

proved The statement and its proof are in Lean. The kernel accepts the proof, and it uses the standard axioms only.

The status is computed from the Lean build. The node of the map.

Something is wrong? Report it.