How Floats Work in a Computer
Floating-point numbers are used to represent real numbers in computers. They are stored in a format similar to scientific notation, consisting of three parts: a sign bit, an exponent, and a significand (or mantissa).
-
Sign Bit: A single bit that determines whether the number is positive (0) or negative (1).
-
Exponent: A field that represents the exponent part of the scientific notation. It is stored in a biased form to allow for both positive and negative exponents. For single-precision (32-bit) floats, the exponent is 8 bits with a bias of 127. For double-precision (64-bit) floats, the exponent is 11 bits with a bias of 1023.
-
Significand: Represents the fractional part of the number in normalized form. In normalized form, the number is represented as 1.xxxx × 2^y, where the leading 1 is implied and not stored. The remaining bits of the significand represent the fractional part after the decimal point.
For example, the number 5.75 is represented in binary as 101.11. Normalized, it becomes 1.0111 × 2^2. The sign bit is 0 (positive), the exponent is 2 plus the bias (127), resulting in 129 (binary 10000001), and the significand is 0111 followed by zeros to fill 23 bits.
Special cases include zero, infinity, NaN (Not a Number), and denormalized numbers for very small values.
Floating-point arithmetic involves aligning exponents, performing operations on the significands, normalizing the result, and handling rounding errors. Due to the finite precision, some decimal numbers cannot be represented exactly, leading to rounding errors.
In summary, floating-point representation allows for a wide range of numbers to be represented efficiently, but with limited precision. This makes it suitable for scientific and engineering calculations where numbers can vary greatly in magnitude.
Thus, floating-point numbers are a trade-off between range and precision, enabling computers to handle a wide variety of numerical values efficiently.