How many representable floats are there between 0.0
and 0.5
? And how many representable floats are there between 0.5
and 1.0
? I'm more interested in the math behind it, and I need the answer for floats
and doubles
.
For IEEE754 floats, this is fairly straight forward. Fire up the Online Float Calculator and read on.
All pure powers of 2 are represented by a mantissa 0
, which is actually 1.0
due to the implied leading 1. The exponent is corrected by a bias, so 1 and 0.5 are respectively 1.0 × 20 and 1.0 × 2−1, or in binary:
S Ex + 127 Mantissa - 1 Hex
1: 0 01111111 00000000000000000000000 0x3F800000
+ 0 + 127 1.0
0.5: 0 01111110 00000000000000000000000 0x3F000000
+ -1 + 127 1.0
Since the floating point numbers represented in this form are ordered in the same order as their binary representation, we only need to take the difference of the integral value of the binary representation and conclude that there are 0x800000 = 223, i.e. 8,388,608 single-precision floating point values in the interval [0.5, 1.0).
Similarly, the answer is 252 for double
and 263 for long double
.