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.2-24

Exercise 1.2.2-24

not stated yet in Lean solution written

Rating15
KindK5, design an algorithm: give a method for a task, often with a cost bound from the written solution
SectionSection 1.2.2 of Volume 1. Companion chapter: Numbers, powers and logarithms

The task

Change the squaring method at the end of the section so that it produces binary logarithms.

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

Ask which steps of the method of Eqs. (17) and (18) depend on the base 1010.

Hint 2

Check Eq. (19) with the new base and look at what the bits bkb_k mean.

Solution

Show the solution

Choose the integer nn with 1≤x/2n<21 \le x/2^n < 2, and set x0=x/2nx_0 = x/2^n. For k≥1k \ge 1 put bk=0, xk=xk−12 if xk−12<2;bk=1, xk=xk−12/2 if xk−12≥2.b_k = 0,\ x_k = x_{k-1}^2 \text{ if } x_{k-1}^2 < 2; \qquad b_k = 1,\ x_k = x_{k-1}^2/2 \text{ if } x_{k-1}^2 \ge 2. Then 1≤xk<21 \le x_k < 2 for all kk, and by induction xk=x2k/22kLkx_k = x^{2^k} / 2^{2^k L_k}, where Lk=n+b1/2+⋯+bk/2kL_k = n + b_1/2 + \cdots + b_k/2^k. The relation 1≤xk<21 \le x_k < 2 gives 2kLk≤2klg⁡x<2kLk+12^k L_k \le 2^k \lg x < 2^k L_k + 1, that is Lk≤lg⁡x<Lk+2−kL_k \le \lg x < L_k + 2^{-k}. So lg⁡x=n+(0.b1b2b3…)2\lg x = n + (0.b_1b_2b_3\ldots)_2.

The method is simpler than the decimal one. The division by 22 is a shift of the binary point, and the bits bkb_k are the binary digits of the logarithm directly, so no binary-to-decimal conversion is needed.

Check

Take x=3x = 3, so n=1n = 1 and x0=1.5x_0 = 1.5. The squares are 2.252.25 (bit 11, x1=1.125x_1 = 1.125), 1.26561.2656 (bit 00), 1.60181.6018 (bit 00), 2.56582.5658 (bit 11) and so on. The bits 1,0,0,1,0,1,0,1,1,11, 0, 0, 1, 0, 1, 0, 1, 1, 1 give lg⁡3≈(1.1001010111)2=1.58496…\lg 3 \approx (1.1001010111)_2 = 1.58496\ldots, and the true value is 1.58496…1.58496\ldots.

Remarks

The same scheme works for any base cc: compare the square with cc and divide by cc. It is natural for c=2c = 2 because the final answer is wanted in binary.

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

In Lean

not stated yet The exercise is not stated in Lean yet.

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

Something is wrong? Report it.