Double precision in C - printing 50 significant figures yields inaccurate values

10,884

Solution 1

The basics of floating-point:

http://en.wikipedia.org/wiki/Floating_point

The answer in your case 0.10 is not exactly representable in binary floating-point. Therefore, it's only accurate to about 16 digits. Yet you are trying to print it out to 50 decimal places.

Solution 2

If you need more accurate results that what double can offer, then you may want to check out some of the arbitrary precision libraries that are available.

Share:
10,884
user992711
Author by

user992711

Updated on June 27, 2022

Comments

  • user992711
    user992711 almost 2 years

    I'm doing an integration program with Riemann sums for my Calculus class. I've decided to use C when computing my integrals, and I noticed a huge error in my program that derives from this problem.

    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    int main(int argc, char** argv) {
    
    double x = 2.0/20.0;
    printf("%1.50f \n", x);
    
    
    return (EXIT_SUCCESS);
    }    
    

    The program gives me : 0.10000000000000000555111512312578270211815834045410. My question: Why does this happen? And how can I fix this? Or at least round off to ~15 decimal places?

    Thanks for the help.