Tuesday, April 28, 2015

increment a C float until it fails: maximum value is about 16,777,216

Higher limit of an incremented float in C

So I finally made it clear. The first increment that has no effect on a C ''float'' variable is around +16,777,216. So four-byte wise, a float still fails later than what I thought compared to a ''uint32_t''.

Note also that the first float to fail on increment is only 16777216.0 vs 4294967295 for a 4 byte integer. When the increments happens each second, it will stop changing after 194 days.

And finally, contrary to increments on integer variables it will not wrap around, which may be quite desirable in some situations.
#include <stdio.h>
#include <stdint.h>
void main()
  float g=-1, f=0;
  while( (long long)f != (long long)g )
  printf("First float to fail: %f vs %u\n",f, (uint32_t)-1);

No comments:

Post a Comment