In python the function random() generates a random float uniformly in the semi-open range [0.0, 1.0). In principle can it ever generate 0.0 (i.e. zero) and 1.0 (i.e. unity)? What is the scenario in practicality?
-
3Not 1.0 surely. Apart from the fact that the range does not include 1.0, there also does not exist a float 1.0 (it can't be represented binary).extraneon– extraneon2010-04-12 09:48:18 +00:00Commented Apr 12, 2010 at 9:48
-
9@extraneon - what? Of course there's a float 1.0. It's '0011111111110000000000000000000000000000000000000000000000000000' (as a double, but the float value is basically the same). The only numbers that don't have an exact float representations are decimals that don't have exact representations with a power-of-two denominator. en.wikipedia.org/wiki/…Daniel G– Daniel G2010-04-12 09:57:17 +00:00Commented Apr 12, 2010 at 9:57
2 Answers
0.0 can be generated; 1.0 cannot (since it isn't within the range, hence the ) as opposed to [).
The probability of generating 0.0 is equal to the probability of generating any other number within that range, namely, 1/X where X is the number of different possible results. For a standard unsigned double-precision floating point, this usually means 53 bits of fractional component, for 2^53 possible combinations, leading to a 1/(2^53) chance of generating exactly 0.0.
So while it's possible for it to return exactly 0.0, it's unlikely that you'll see it any time soon - but it's just as unlikely that you'd see exactly any other particular value you might choose in advance.