Floating-point numbers are a way to represent real numbers in a binary format, similar to how scientific notation works in decimal. They are widely used in computing for their ability to represent a wide range of values (both very large and very small) with a fixed number of bits. However, they come with trade-offs, such as limited precision and potential rounding errors.
Floating-Point Representation (IEEE 754 Standard)
The most common floating-point representation is defined by the IEEE 754 standard, which specifies formats like:
- Single-precision (32-bit)
- Double-precision (64-bit)
- Extended-precision (80-bit, 128-bit, etc.)
We'll focus on single-precision (32-bit) for explanation.
Structure of a 32-bit Floating-Point Number
A 32-bit floating-point number is divided into three parts:
- Sign bit (1 bit) – Determines if the number is positive (
0) or negative (1).
- Exponent (8 bits) – Represents the scale of the number (similar to the exponent in scientific notation).
- Mantissa (Fraction) (23 bits) – Represents the significant digits of the number.
| Sign (1 bit) | Exponent (8 bits) | Mantissa (23 bits) |
|---------------|--------------------|--------------------|
| 0 or 1 | 8 bits | 23 bits |
How It Works
-
Scientific Notation Analogy
-
Normalized vs. Denormalized Numbers
- Normalized numbers have a leading
1 before the binary point (hidden bit), so the mantissa stores the remaining bits.
- Example:
1.1011 × 2^5 is stored as exponent = 5 + 127 = 132 (binary 10000100), and mantissa = 1011... (23 bits).
- Denormalized numbers (when exponent is all zeros) have no hidden bit, so the mantissa represents a number between
0 and 1.
-
Special Cases
- Zero: Exponent = all zeros, mantissa = all zeros.
- Infinity: Exponent = all ones, mantissa = all zeros.
- NaN (Not a Number): Exponent = all ones, mantissa ≠ all zeros.
Precision and Rounding Errors
- Floating-point numbers have finite precision, meaning they can only represent a limited number of distinct values.
- Some decimal numbers (like
0.1) cannot be represented exactly in binary, leading to rounding errors.
- Operations like addition and multiplication can accumulate these errors.
Example: Storing 6.5 in 32-bit Float
- Convert
6.5 to binary:
6 = 110 (integer part)
0.5 = 0.1 (fractional part)
- Combined:
110.1 (binary)
- Normalize to
1.101 × 2^2
- Store:
- Sign bit:
0 (positive)
- Exponent:
2 + 127 = 129 → 10000001 (binary)
- Mantissa:
10100000000000000000000 (23 bits, after the hidden 1)
Conclusion
Floating-point numbers are a powerful but imperfect way to represent real numbers in computers. They allow for a wide range of values but introduce precision issues due to their finite binary representation. Understanding their internal structure helps in debugging numerical errors in programs.