Home >Backend Development >C++ >Why Do Double-Precision Numbers Seem More Precise Than 15 Decimal Places?

Why Do Double-Precision Numbers Seem More Precise Than 15 Decimal Places?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 18:04:16641browse

Why Do Double-Precision Numbers Seem More Precise Than 15 Decimal Places?

Double Precision Decimal Places

Question:

Despite documentation suggesting that double precision values have a precision of 15 decimal places, internal values often exhibit more precision. Why is this discrepancy observed?

Answer:

IEEE doubles have 53 significant bits, providing approximately 15.95 decimal digits of precision (based on the formula log10(253)). This theoretical precision is slightly greater than the 15 decimal digits indicated by the DBL_DIG constant. The additional precision is accounted for by the extra significant bit.

The nextafter() function demonstrates the true precision of a given double. By calculating the nearest representable numbers to a given value, it reveals that double precision values typically have 16 significant digits.

Here's a program that illustrates this:

#include <cstdio>
#include <cfloat>
#include <cmath>

int main() {
    double x = 1.0/7.0;
    printf("FLT_RADIX = %d\n", FLT_RADIX);
    printf("DBL_DIG = %d\n", DBL_DIG);
    printf("DBL_MANT_DIG = %d\n", DBL_MANT_DIG);
    printf("%.17g\n%.17g\n%.17g\n", nextafter(x, 0.0), x, nextafter(x, 1.0));
}

The output typically shows that:

  • 1.0/7.0 is represented with approximately 16 significant digits.
  • The last hexadecimal bit alternates between 0 and 1 for consecutive values.
  • The mathematical value of 1.0/7.0 (0.142857142857142857) is only represented approximately in double precision.

The above is the detailed content of Why Do Double-Precision Numbers Seem More Precise Than 15 Decimal Places?. 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