Home >Backend Development >C++ >Why Doesn't 0.1 Equal 0.1 in Floating-Point Arithmetic?
Floating-Point Numbers: Understanding the Discrepancy Between 0.1 and its Computer Representation
Floating-point arithmetic is fundamental in computer science, but the way numbers like 0.1 are stored can be counterintuitive. This explanation clarifies the representation process.
The IEEE 754 standard dictates that floating-point numbers are composed of a sign bit, an exponent, and a mantissa. Let's examine the binary representation of 0.1:
<code>0 | 01111011 | 10011001100110011001101</code>
Here's the breakdown:
The exponent signifies multiplication by 2-4. The mantissa represents the fractional portion. Adding these components yields approximately 1.60000002384185791015625. Multiplying by 2-4 gives 0.100000001490116119384765625, a close approximation of 0.1.
Decimal representation follows a similar pattern. For example, 0.8125 is stored as:
<code>0 | 01111110 | 10100000000000000000000</code>
The exponent indicates multiplication by 2-1. The mantissa, 1.101, equals 13/8. Therefore, 13/8 * 1/2 = 0.8125.
This detailed representation highlights why seemingly simple decimal numbers like 0.1 have slightly different floating-point equivalents. This slight inaccuracy is inherent in the system and crucial to understanding numerical computations within computer systems. The method ensures computational accuracy and efficiency.
The above is the detailed content of Why Doesn't 0.1 Equal 0.1 in Floating-Point Arithmetic?. For more information, please follow other related articles on the PHP Chinese website!