Floating-point numbers
The conceptWhy 0.1 + 0.2 doesn't quite equal 0.3 on a computer
Computers store most non-whole numbers as floating-point numbers: a fixed number of binary digits plus a power of two that says where the binary point sits. It works like scientific notation (3.1 × 10⁵), but in base 2.
A float has three parts: a sign bit for plus or minus, exponent bits that pick the power of two, and fraction bits (the mantissa) that hold the digits. A 32-bit float uses 1, 8 and 23 bits for these.
In binary, 0.1 is 0.000110011… with the pattern repeating forever, much as 1/3 repeats in decimal. The computer has to cut it off and round, so 0.1 is stored as a value very slightly off.
What it’s forTurns the stored bits of a float back into the number they stand for.
value = (−1)ˢ × (1 + f) × 2^(e − bias)
- s
- sign bit: 0 for positive, 1 for negative
- f
- the fraction bits read as a binary fraction between 0 and 1
- e
- the stored exponent bits read as a whole number
- bias
- a fixed offset so exponents can be negative; 127 for 32-bit floats
What it givesThe real number the bits represent: a precise significant part times a power-of-two scale.
- 0.75 = 1.5 × 0.5, so s = 0, f = 0.5, and e − bias = −1
- In a 32-bit float the stored exponent is e = 127 − 1 = 126
- Check: (1 + 0.5) × 2⁻¹ = 1.5 × 0.5 = 0.75