Home >Backend Development >C++ >Why Doesn't 0.1 Equal 0.1 in Floating-Point Arithmetic?

Why Doesn't 0.1 Equal 0.1 in Floating-Point Arithmetic?

Barbara Streisand
Barbara StreisandOriginal
2025-01-15 08:49:46915browse

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:

  • Sign: 0 (positive)
  • Exponent (biased): 123 (123 - 127 bias = -4)
  • Mantissa: 1.0011001100110011001101 (1 plus fractional components)

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>
  • Sign: 0 (positive)
  • Exponent (biased): 126 (126 - 127 bias = -1)
  • Mantissa: 1.101 (integer and fractional parts)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn