Floating point puzzle
mcdonald at uxe.cso.uiuc.edu
mcdonald at uxe.cso.uiuc.edu
Sun Aug 7 23:13:00 AEST 1988
I tried running the following program on my IBM PC, using Microsoft C 5.1
with command line switch /Od - no optimization.
#include <stdio.h>
main()
{
union {
float fl;
unsigned long lo;
} x,y;
x.fl = 1.0/10.0;
y.fl = 1677721.0/16777216.0;
printf("x: %lx", x.lo);
printf("%20.17f\n",x.fl);
printf("y: %lx", y.lo);
printf("%20.17f\n",y.fl);
}
/* output is:
x: 3dcccccd 0.10000000149011610
y: 3dccccc8 0.09999996423721313
/*
Which is exactly what I would expect. The first one is 0.1 to almost
8 places, while the second is a bit smaller - just as it should be.
Try running this program, or, if your compiler has 32bit ints,
substitute "int" for "long" and "%x" for %lx".
Doug McDonald
More information about the Comp.lang.c
mailing list