Home > Backend Development > C++ > Why is 0.1 not represented exactly in floating-point arithmetic, while 0.5 is?

Why is 0.1 not represented exactly in floating-point arithmetic, while 0.5 is?

Mary-Kate Olsen
Release: 2025-01-15 07:49:13
Original
137 people have browsed it

Why is 0.1 not represented exactly in floating-point arithmetic, while 0.5 is?

Floating-Point Precision: Why 0.5 is Exact, but 0.1 Isn't

Floating-point arithmetic, while efficient for many computations, faces inherent limitations in precisely representing all decimal numbers. This article explores why 0.5 enjoys exact representation while 0.1 does not.

Understanding the Representation of 0.1

The IEEE 754 standard dictates how floating-point numbers are stored. Let's examine 0.1's representation:

<code>s eeeeeeee mmmmmmmmmmmmmmmmmmmmmmm
0 01111011 10011001100110011001101</code>
Copy after login
  • Sign (s): 0 (positive).
  • Exponent (eeeee): 123. Subtracting the bias (127), we get an effective exponent of -4.
  • Mantissa (mmmmmmmmmmmmmmmmmmmmmm): Interpreted as a binary fraction with an implicit leading "1." The sum of the mantissa bits yields approximately 1.60000002384185791015625.

Multiplying the mantissa by 2-4 gives roughly 0.100000001490116119384765625. This is a close approximation of 0.1, but not an exact match. The inherent limitations of binary representation prevent a perfect conversion from the decimal 0.1.

The Precise Representation of 0.5

In contrast, 0.5 has a straightforward representation:

<code>s eeeeeeee mmmmmmmmmmmmmmmmmmmmmmm
0 01111110 00000000000000000000000</code>
Copy after login
  • Sign (s): 0 (positive).
  • Exponent (eeeee): 126. The effective exponent (after bias adjustment) is -1.
  • Mantissa (mmmmmmmmmmmmmmmmmmmmmm): 0.

This translates to 1 * 2-1 = 0.5, a perfect representation.

Conclusion: The Limits of Binary Precision

The difference lies in the ability of the binary system to represent certain decimal fractions exactly. While 0.5 (1/2) is a power of two and thus easily represented in binary, 0.1 (1/10) is not. This results in a slight rounding error when storing 0.1 in floating-point format, leading to the approximation observed. Programmers must be mindful of this inherent limitation when working with floating-point numbers and precision-sensitive applications.

The above is the detailed content of Why is 0.1 not represented exactly in floating-point arithmetic, while 0.5 is?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template