0

Consider the following code:

#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <errno.h>
#include <float.h>

int main (void) {
    double val;
    /* base b = 2; 2^DBL_MANT_DIG */
    /* decimal digits log10(2^DBL_MANT_DIG) */
    /*const char *str = "9007199254740992";*/
    const char *str = "9007199254740993";

    errno = 0;
    val = strtod(str, NULL);

    printf("%d\n", DBL_MANT_DIG );

    if (errno == ERANGE) {
        printf("error\n");
    } else {
        printf("%f\n", val);
    }

    return 0;
}

This returns:

53
9007199254740992.000000

Since str has a string number that has more significant digits than the my machine can handle, how does one use DBL_MANT_DIG or the log10(2^DBL_MANT_DIG) version of it to check that the result of val is correct?

1 Answers1

1

You don't use those to check that the conversion is exact.

Here's one way of how to do it.

Another way is to find out how many decimal digits after the decimal point are there in the resultant double, do sprintf() using that as the precision and compare its output with the original string.

Community
  • 1
  • 1
Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
  • thanks for you suggestions, it's somewhat more complicated than what I hoped for but I'll surely check them out. I'll see if other people perhaps have further suggestions. –  Apr 14 '13 at 13:55
  • It's not a trivial problem. [A must read](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – Alexey Frunze Apr 14 '13 at 13:56
  • Yes, thanks, I know that paper and am reading it. I thought since this must be such a common problem that perhaps there is a library or some such. –  Apr 14 '13 at 15:36
  • When using floating point, fewer people care about precise results than care about consistent results. [Consistency: how to defeat the purpose of IEEE floating point](http://www.yosefk.com/blog/consistency-how-to-defeat-the-purpose-of-ieee-floating-point.html). – Alexey Frunze Apr 14 '13 at 15:41