Why does 0.375 convert to binary in three clean steps while 0.1 explodes into ~50 bits that never settle?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
The binary fraction 0.101 means 1/2 + 0/4 + 1/8 — each digit after the point switches
on a negative power of two. Its three digits are given below, left to right. Compute the
decimal value of 0.101 and assign it to value.
(Hint: the place values after the point are 1/2, 1/4, 1/8, and / does ordinary
division.)
The meaning of a base-2 fraction 0.abc
Write that 0.abc in base 2 is a/2 + b/4 + c/8, next to the base-10 reading a/10 + b/100 + c/1000, with each digit 0 or 1.
The multiply, convert and shift recipe
List the three steps and work 0.375 through them: multiply by 2**3 to reach 3, convert 3 to 11, then move the point three places left for 0.011.
Hand-trace of the code on 0.625
Trace the loop that raises p while the remainder stays non-zero, through 0.625, 0.25 and 0.5, stopping at p = 3 with num = 5, then 101 and finally 0.101.
Fractions with no short binary form
Record that 0.1 must be multiplied by roughly 2**50 before it becomes whole, giving about fifty digits, and that other fractions run longer still, potentially infinite.