OP's code is not exactly assigning value as perceived. double
can only represent a finite set of numbers. It will use the closest representable double. Typically double
can accurately represent at least the first 15 signification decimal digits, or 110020030040050xxxx.xxxx
1100200300400500600.0000000001
lies between two double
:
1100200300400500480
and
1100200300400500608
.
// Add d1 to the closest representable double. This turns out to be _exactly
// 1100200300400500608
double d1 = 1100200300400500600.0000000001;
double d2 = 1100200300400500600.0000000001;
// adding those 2 result in the _exact
// 2200400600801001216
double d3 = d1 + d2;
// To print to 10 decimal places
printf("%.10f", d3);
// 2200400600801001216.0000000000
With typical floating point, to print the value exactly, use
printf("%a\n", d3);
To print a double
in decimal with sufficient accuracy to distinguish all double
, use
printf("%.e\n", DBL_DECIMAL_DIG - 1, d3);