Floating Point
Teens & adults Computing Number systems
Computers store decimals in binary fractions — 1/2, 1/4, 1/8…
Some decimals have no exact binary form. 0.1 is like
1/3 in decimal: an infinite repeat (0.0001100110011…₂). The
computer rounds it off — and the tiny error becomes visible:
0.1 + 0.2 = 0.30000000000000004 ← every computer on Earth
Float vs double
- F32 (float) — 32 bits ≈ 7 decimal digits of precision
- F64 (double) — 64 bits ≈ 15 digits; the default choice
Rules for staying sane
- Never compare floats with
=— check |a − b| < 0.0001 instead - Money: count cents in integers, display dollars at the end — $19.99 stored as 1999
- Game physics and graphics: floats are fine — the error is invisible per-frame
In ALB
ALB offers
PURE/RATIONAL types that store
exact fractions instead of binary approximations — 1/3 stays
exactly 1/3. Where that isn't available, integer cents are the
professional trick.
Practice
Why does 0.1 + 0.2 print 0.30000000000000004?
Store $9.99 safely as:
Compare two floats a and b with:
Next: modular arithmetic · Back: binary & hex