how many whole numbers in IEEE 754

后端 未结 2 1761
一个人的身影
一个人的身影 2020-12-11 23:27

I am trying to figure out how many different whole numbers exist in the ieee 754. The number I got was 1778384895 but I couldn\'t find any resource to check myself. Thanks a

相关标签:
2条回答
  • 2020-12-11 23:55

    I agree with Jester's answer. As a cross-check, and to demonstrate an alternative approach, I wrote, in Java, a brute force scan of all the finite float numbers, counting the ones that are integers. Math.nextUp returns the smallest positive float for either form of zero, so zero only gets counted once.

    public class Test {
      public static void main(String[] args) {
        long count = 0;
        for (float f = -Float.MAX_VALUE; f <= Float.MAX_VALUE; f = Math.nextUp(f)) {
          if (Math.rint(f) == f) {
            count++;
          }
        }
        System.out.println(count);
      }
    }
    

    It output 1778384895

    0 讨论(0)
  • 2020-12-12 00:12

    I will assume single precision floats.

    We got the zero, which although can be represented as negative zero, is still just zero as an integer so I count it as one.

    Numbers with exponent less than 127 are not integers.

    Exponent   Free bits   # Numbers
    127        0           1
    128        1           2
    129        2           4
    ...
    149        22          2^22
    

    These sum up to 2^23-1. If exponent is greater than 149, all the numbers are integers. So that's an additional 105*2^23 numbers (exponent 255 is reserved). All of these come in positive and negative.

    The grand total is thus

    1 + ((2^23 - 1) + 105 * (2^23)) * 2 = 1778384895
    

    So looks like you were right. Nice question, it looked a lot easier at first sight :)

    0 讨论(0)
提交回复
热议问题