Floating point: how computers store fractions
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Computers store numbers like 6.25 and 0.1 as floating point: a sign, an exponent and a fraction, packed into a fixed number of bits. Follow 6.25 as it is written in binary (110.01), normalised by sliding the point (1.1001 × 2²) and packed into the 16 bits of a half-precision float. Then see why 0.1 cannot be stored exactly, and why 0.1 + 0.2 is not 0.3 in Python.
Scientific notation
Scientists write 6250 as 6.25 × 10³: a few digits, times a power of ten. The power says where the decimal point goes. A floating-point number works the same way, but in base 2. Our example is 6.25.
>>> 6.25e3 # 6.25 × 10**3 6250.0 >>> 6250 / 10**3 6.25
اقرأ الدرس خطوة بخطوة
Scientific notation
Scientists write 6250 as 6.25 × 10³: a few digits, times a power of ten. The power says where the decimal point goes. A floating-point number works the same way, but in base 2. Our example is 6.25.
>>> 6.25e3 # 6.25 × 10**3 6250.0 >>> 6250 / 10**3 6.25Bits after the point
In binary, places left of the point are worth 4, 2 and 1. Places right of it are halves: ½, ¼, ⅛. Take out each place that fits: 6.25 = 4 + 2 + ¼. So 6.25 is 110.01 in binary.
>>> 4 + 2 + 1/4 6.25 >>> 0b11001 / 2**2 # 110.01: the point 2 places in 6.25Float the point
Now slide the point left until one 1 stands in front of it: 110.01 becomes 1.1001. Each move halves the value, so we multiply by 2 to keep the value: 6.25 = 1.1001 × 2². This is called normalising.
>>> 0b11001 / 2**4 # 1.1001 in binary 1.5625 >>> 1.5625 * 2**2 6.25The sign bit
A float packs three fields into a row of bits. We use the 16-bit half-precision format: 1 sign bit, 5 exponent bits and 10 fraction bits. The sign bit is 0 for plus and 1 for minus. 6.25 is positive: 0.
>>> from struct import pack >>> pack('>e', 6.25).hex() '4640' >>> pack('>e', -6.25).hex() # only the sign bit flips 'c640'Exponent plus a bias
The exponent 2 is stored with a bias of 15 added, so it never needs a minus sign: 2 + 15 = 17. In 5 bits, 17 is 10001. With this bias, normal numbers use exponents −14 to +15.
>>> 2 + 15 17 >>> format(17, '05b') '10001'The hidden 1
After normalising, the digit before the point is always 1, so it is not stored: it is the hidden bit. The 10 fraction bits keep the digits after the point, 1001, and zeros fill the rest: 1001000000.
>>> format(0b1001 << 6, '010b') # 1001, then six 0s '1001000000'Read it back
To read the bits, undo each step. Sign 0: plus. Exponent 17 − 15 = 2. Fraction: put the hidden 1 back, 1.1001 = 1 + ½ + 1/16 = 1.5625. Then 1.5625 × 2² = 6.25. Python's struct agrees: hex 4640.
>>> (1 + 0b1001000000 / 2**10) * 2**(17 - 15) 6.25 >>> from struct import unpack >>> unpack('>e', bytes.fromhex('4640'))[0] 6.250.1 never ends
Now try 0.1. In binary it is 0.000110011001100…, and the 1100 pattern never ends, just as 1/3 = 0.333… never ends in decimal. Normalised, 0.1 = 1.1001 1001 1001… × 2⁻⁴.
>>> 1/3 0.3333333333333333 >>> format(0.1, '.20f') # Python's 0.1 is not exact '0.10000000000000000555'Cut off and rounded
Store 0.1 the same way: sign 0, exponent −4 + 15 = 11. Only the first 10 fraction bits fit: 1001100110. The rest is rounded away, so the half float holds 0.0999755859375 (hex 2e66), a little less than 0.1.
>>> from struct import pack, unpack >>> pack('>e', 0.1).hex() '2e66' >>> unpack('>e', pack('>e', 0.1))[0] 0.0999755859375Python floats: 64 bits
Python's float uses the 64-bit double format: 1 sign bit, 11 exponent bits and 52 fraction bits. That is far more precise, but 0.1 is still not exact, so 0.1 + 0.2 gives 0.30000000000000004.
>>> 0.1 + 0.2 0.30000000000000004 >>> 0.1 + 0.2 == 0.3 False >>> import math >>> math.isclose(0.1 + 0.2, 0.3) TrueThe same fields, wider
(6.25).hex() writes a double as hex digits times a power of two: '0x1.9000000000000p+2'. The 1 is the hidden bit, hex 9 is binary 1001, and p+2 means × 2². A double's bias is 1023, so it stores 2 + 1023 = 1025.
>>> (6.25).hex() '0x1.9000000000000p+2' >>> float.fromhex('0x1.9p+2') 6.25 >>> 2 + 1023 # the double stores this exponent field 1025 >>> import sys >>> sys.float_info.mant_dig # 52 stored bits + the hidden 1 53
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01What is the binary number 10.1 in decimal?
The 1 left of the point is in the 2s place and the 1 right of it is in the ½ place: 2 + 0.5 = 2.5.
02Normalised, 110.01 (6.25) becomes 1.1001 × 2². What does the exponent 2 record?
The point slid two places left, which divides the digits by 2 twice, so the number is multiplied by 2² to keep its value.
03Half precision adds a bias of 15 to the exponent. Which 5-bit pattern stores the exponent 3?
3 + 15 = 18, and 18 = 16 + 2 is 10010 in binary. The bias means the field never has to hold a negative number.
04Why is the leading 1 of a normalised number not stored?
After normalising, every (normal) number starts with 1. Leaving it out, as a hidden bit, gives one extra bit of precision for free.
05In Python, 0.1 + 0.2 == 0.3 gives False. What is the best way to compare them?
0.1 and 0.2 are both rounded in binary, so the sum is 0.30000000000000004. math.isclose() checks that two floats are equal within a small tolerance.
المسرد
- Floating point
- A way to store numbers as a sign, a significand (the digits) and an exponent (where the point goes), so the point can 'float'.
- Binary point
- The point in a binary number. Places to its left are 1, 2, 4 …; places to its right are ½, ¼, ⅛ …
- Normalise
- Slide the point until exactly one non-zero digit (in binary, a 1) is in front of it, and record the move in the exponent: 110.01 = 1.1001 × 2².
- Exponent bias
- A fixed number added to the exponent before it is stored (15 for half precision, 1023 for double), so the field never holds a negative number.
- Hidden bit
- The leading 1 of a normalised binary number. It is always 1, so it is not stored.
- Fraction (mantissa)
- The stored digits after the binary point of the normalised number. IEEE 754-2019 calls it the trailing significand field; "mantissa" is the common informal name.
- Rounding error
- The small difference between a number and the nearest value a float can hold, for example 0.1 stored as 0.0999755859375 in half precision.
- Double precision
- The 64-bit IEEE 754 format used by Python's float: 1 sign bit, 11 exponent bits, 52 fraction bits.
الملاحظات والمصادر
- IEEE 754 defines the common formats. Half precision (binary16) has 1 sign, 5 exponent and 10 fraction bits, bias 15. Single (binary32) has 1, 8 and 23, bias 127. Double (binary64), Python's float, has 1, 11 and 52, bias 1023.
- Two exponent patterns are reserved. All 0s means zero or a tiny "subnormal" number with no hidden 1; all 1s means infinity or NaN (not a number). That is why half-precision exponents run only from −14 to +15.
- By default IEEE 754 rounds to the nearest value it can store (a tie goes to the one ending in 0). For 0.1, the bits after the tenth fraction bit start 011…, less than half a place, so it rounds down.
- More exponent bits give more range; more fraction bits give more precision. The largest half-precision number is 65504 and it keeps about 3 significant decimal digits; a double reaches about 1.8 × 10³⁰⁸ with 15 to 17 digits.
- Because decimal fractions like 0.1 are not exact in binary, money is usually kept in whole cents or in Python's decimal module.
- IEEE 754-2019, IEEE Standard for Floating-Point Arithmetic
- D. Goldberg, What Every Computer Scientist Should Know About Floating-Point Arithmetic (ACM Computing Surveys, 1991)
- Harris & Harris, Digital Design and Computer Architecture, 2nd ed., section 5.3.2 Floating-Point Numbers
- Python tutorial: Floating-point arithmetic, issues and limitations
- Python library: struct (format 'e', IEEE 754 binary16)
- Python library: float.hex() and float.fromhex()
- Python library: math.isclose()
اختبار يتاح بعد الخطوة الأخيرة.