0

I'm trying to figure out how many numbers between 0-1 can a 32bit floating point represent? is it just the same as in an interval? (2**24)-1

Mark Dickinson
  • 29,088
  • 9
  • 83
  • 120
Niv Peretz
  • 19
  • 3

1 Answers1

3

That number happens to be 1,056,964,609. (Excluding -0). This only accounts for normal numbers. If you also include subnormals, then the number is 1,065,353,217. You can count them with a program like this:

#include <math.h>
#include <stdio.h>

int main(void) {
   float x = 0.0f;
   int normals = 0;
   int all     = 0;

   while (x <= 1.0) {
     all++;
     if(isnormal(x)) normals++;
     x = nextafterf(x, 1.1);
   }

   printf("normals: %d\n", normals);
   printf("all    : %d\n", all);

   return 0;
}

When run, this prints:

normals: 1056964609
all    : 1065353217

It's interesting to note that a quarter of all normal floats live in this range. This is usually quite a surprise and can have implications in uniform random-number generation.

See https://lemire.me/blog/2017/02/28/how-many-floating-point-numbers-are-in-the-interval-01/ for details.

alias
  • 28,120
  • 2
  • 23
  • 40
  • 1
    That's excluding subnormals, right? (But incuding `0.0` and `1.0` (and excluding `-0.0`).) – Mark Dickinson Nov 19 '21 at 19:41
  • 1
    @MarkDickinson Quite right; updated the answer to include denormals as well. – alias Nov 19 '21 at 19:46
  • Note that 1,065,353,216 excludes one of 0 or 1. – Eric Postpischil Nov 19 '21 at 21:04
  • 1
    The preferred term for numbers below the normal range is “subnormal”: These are numbers that are below the normal range, so they can only have denormalized representations. “Denormal” refers to a floating-point representation that is not normal. In IEEE-754 binary formats, the only denormalized representations are those for subnormal numbers. In decimal formats, numbers in the normal range can have normal or denormal representations. – Eric Postpischil Nov 19 '21 at 21:14
  • @EricPostpischil Quite right. Fixed the naming and also added a simple program to count the values. – alias Nov 19 '21 at 21:20