浮點數如何儲存,以及為何 0.1 無法精確表示
How floating-point numbers are stored (and why 0.1 isn't exact)
IEEE 754 以符號位、指數和尾數儲存浮點數,因此二進制小數無法有限表示的 0.1 會被捨入,並使 0.1 + 0.2 得出 0.30000000000000004。文章以 float32 和 float64 示範 5.75 如何精確儲存、0.1 如何產生表示誤差,並説明比較浮點數時應使用容差,金額則不應以二進制浮點數儲存。
Disclosure: this post was written with AI assistance and checked by the FlashKit team.
Open any console and type 0.1 + 0.2. You get 0.30000000000000004.
This is not a bug in Python, JavaScript or your browser. It is what happens when a number with a repeating binary expansion is squeezed into a fixed number of bits. Once you can read the bits of a float by hand, the "surprise" stops being one. This post does that for two numbers: 5.75, which is stored exactly, and 0.1, which is not.
Three fields in 32 or 64 bits
IEEE 754 stores a float as three fields: a sign bit, an exponent and a mantissa (also called the fraction or significand).
| Format | Sign | Exponent | Mantissa | Exponent bias |
|---|---|---|---|---|
| float32 (binary32) | 1 bit | 8 bits | 23 bits | 127 |
| float64 (binary64) | 1 bit | 11 bits | 52 bits | 1023 |
For a normal number, the value is:
(-1)^sign × 1.mantissa × 2^(exponent - bias)
Two details trip people up. The leading 1. is not stored; it is implied, which buys one extra bit of precision. And the exponent is stored with an offset (the bias), so a stored exponent of 129 in float32 means 129 − 127 = 2.
Two exponent patterns are reserved. An all-zeros exponent means zero or a subnormal number (the leading bit is 0 instead of the implied 1, which fills the gap near zero). An all-ones exponent means infinity when the mantissa is zero and NaN otherwise. Everything in this post uses normal numbers, so you can ignore those two cases for now.
Example 1: 5.75, stored exactly
Convert 5.75 to binary in two parts. The integer part 5 is 101. The fraction 0.75 is 0.5 + 0.25, which is .11. So 5.75 = 101.11 in binary.
Normalise it so there is a single 1 before the point: 101.11 = 1.0111 × 2^2.
- Sign: positive, so
0. - Exponent: 2 + 127 = 129 =
10000001. - Mantissa: the digits after the point,
0111, padded with zeros to 23 bits:01110000000000000000000.
Put together, 5.75 as float32 is:
0 10000001 01110000000000000000000
Grouped in fours that is 0100 0000 1011 1000 0000 0000 0000 0000, or 0x40B80000 in hex.
5.75 is exact because it equals 23/4, and the denominator is a power of two. Any number that is a whole number divided by a power of two fits in the mantissa, as long as it has few enough significant bits.
Example 2: 0.1, which cannot be exact
Now try 0.1. Repeatedly doubling the fraction (the same method used for converting decimal fractions to binary by hand) gives:
0.1 = 0.0001100110011001100110011...
The block 0011 repeats forever, just like 1/3 = 0.333… repeats in decimal. A decimal fraction can only be written exactly in binary if its denominator, in lowest terms, is a power of two. 1/10 has a factor of 5 in the denominator, so it never terminates.
Normalise: 0.0001100110011… = 1.100110011… × 2^-4.
- Sign:
0. - Exponent: −4 + 127 = 123 =
01111011. - Mantissa: the 23 bits after the point are
10011001100110011001100, and the bits that follow begin1100….
Those leftover bits are more than half of the last place, so the stored mantissa is rounded up to 10011001100110011001101. The result:
0 01111011 10011001100110011001101 = 0x3DCCCCCD
What number is that, exactly? Not 0.1:
0.100000001490116119384765625
The error is about 1.49 × 10⁻⁹. You can reproduce it in Python:
import struct
from decimal import Decimal
bits = struct.unpack(">I", struct.pack(">f", 0.1))[0]
print(hex(bits)) # 0x3dcccccd
f32 = struct.unpack(">f", struct.pack(">I", bits))[0]
print(Decimal(f32)) # 0.100000001490116119384765625
float64 has the same problem, just further out
Most languages use float64 by default (JavaScript's Number, Python's float). The same procedure gives:
0 01111111011 1001100110011001100110011001100110011001100110011010 = 0x3FB999999999999A
and the exact value stored is:
0.1000000000000000055511151231257827021181583404541015625
That is slightly above 0.1. In fact it is exactly 3602879701896397 / 2^55. More bits mean a smaller error, but never zero.
So why does 0.1 + 0.2 print 0.30000000000000004?
Both inputs are already rounded:
0.1 → 0.1000000000000000055511151231257827…
0.2 → 0.2000000000000000111022302462515654…
Their exact sum is 0.3000000000000000166533453693773481…, which is not a float64 either. It sits halfway between two neighbouring doubles:
0x3FD3333333333333 = 0.299999999999999988897769753748… (what the literal 0.3 gives)
0x3FD3333333333334 = 0.300000000000000044408920985006… (the answer)
The sum lands in an exact tie, and IEEE 754's default rule (round half to even) picks the one whose last bit is 0, which is the …334 neighbour. That is 0.30000000000000004 when printed with enough digits to tell it apart from 0.3. Two different floats, so 0.1 + 0.2 == 0.3 is False.
You can check the tie yourself:
from fractions import Fraction as F
s = F(0.1) + F(0.2)
print(s - F(0.3) == F(0.1 + 0.2) - s) # True
What to do about it
-
Don't compare floats with
==. Compare with a tolerance, such asmath.isclose(a, b)in Python, or an epsilon scaled to the size of the numbers. -
Don't store money as binary floats. Use integer cents or a decimal type (
decimal.Decimal,BigDecimal). - Know your width. float32 gives you roughly 7 significant decimal digits. The integer 16,777,217 (2^24 + 1) does not fit in float32's 24-bit significand, so it is stored as 16,777,216. float64 gives roughly 15 to 16 digits.
- Printing is not storage. Shortest-round-trip printing (what JavaScript and modern Python do) hides most of the noise. The exact stored value is still there.
Check the bits yourself
Doing this by hand once is worth it, but you do not need to repeat it for every number. These free, in-browser tools show the same working. None of them need a sign-up, and nothing you type is uploaded:
- The IEEE 754 float converter shows float32 and float64 bits colour-coded into sign, exponent and mantissa, the hex, the exact stored decimal and the rounding error. You can click any bit to toggle it. Try
0.1,5.75and3DCCCCCD. - The decimal to binary converter does the divide-by-2 and multiply-by-2 steps, including repeating fractions like
0.0(0011). - The binary to hex converter is the "group the bits in fours" step used above.
We also wrote a shorter explainer on the same topic: why 0.1 cannot be stored exactly in binary.
Disclosure: we build FlashKit, the site behind these tools. It is free and ad-supported.
來源:DEV Community · dev.to