mercredi 15 juin 2016

Generating random integers uniformly in log space

I want to generate random integers which are uniformly distributed in log space. That is, the log of the values of will be uniformly distributed.

A normal uniformly distributed unsigned int will have 75% of its magnitudes above 1 billion, and something like 99.98% above 1 million, so small values are underrepresented. A uniform value from log space would have the same number of values in the range 4-8, as 256-512, for example.

Ignoring negative values for now, one way I can think of is something like:

Random r = new Random();
return (int)Math.pow(2, r.nextDouble() * 31);

That should generate a 31-bit log-uniformly distributed. It's not going to be fast though, with an pow() operation in there and to introduce floating point values to generate integers is a bit of a smell. Furthermore, a lot of the range of double is lost by Random.nextDouble() and it is not clear to me if this code can even generate all 2^31-1 positive integer values.

Better solutions welcome.

Aucun commentaire:

Enregistrer un commentaire