tags:

views:

148

answers:

2

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?

+9  A: 

The [ indicates that 0.0 is included in the range of valid outputs. The ) indicates 1.0 is not in the range of valid outputs.

Hank Gay
+9  A: 

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.

Amber
@Dav: Just a nitpick for what's already a nice answer, but I think you mean 53, not 52. With a perfect random source (which Mersenne Twister of course is not, but it's good enough for practical non-cryptographic purposes), random() generates a number of the form n/2^53 with n an integer uniformly and randomly chosen in the range [0, 2^53). If you look at the source, it takes two 32-bit words generated by the MT algorithm and combines the top 27 bits of the first with the top 26 bits of the second to create n.Incidentally, this means that most floats in [0.0, 1.0) can't ever be generated.
Mark Dickinson
Ah, right - probably because I was thinking of signed floating point, and random() probably uses an unsigned format given its range. I'll change it.
Amber
@Mark Dickinson : 2^52 is a troublesome number in MATLAB ! ..... does it also employ Mersenne Twister ?
Arkapravo
@Arkapravo: It looks like it, at least for not-too-old versions. The release notes for MATLAB 7.4 (released March 2007) say: "rand Function Uses the Mersenne Twister Algorithm as Default".
Mark Dickinson
@Mark Dickinson : Yep ! ..... I am using 7.9.0 ... I will check out the notes !
Arkapravo
@Mark Dickinson: I understand that Mersenne Twister is a significant improvement on Wichmann-Hill generator to generate random numbers ! ... anything more newer than the Twister ?
Arkapravo
@Arkapravo: Sure; it's an area of active research. There are recent PRNGs that claim to have better equidistribution properties, better bit-mixing, longer period, faster generation (e.g. by making good use of SIMD instructions), etc. I don't think any of these PRNGs has established itself as an obvious successor to MT, though.If you're not doing crypto, I'd be surprised if MT isn't good enough for your needs.
Mark Dickinson
@Mark Dickinson: I am not into crypto ! ... just inquisitive ! :)
Arkapravo