Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random numbers on open-open interval (0,1) efficiently

I'm looking for an efficient way to generate random floating-point numbers on the open-open interval (0,1). I currently have an RNG that generates random integers on the closed-closed interval of [0, (2^32)-1]. I've already created a half-open floating point RNG on the interval [0,1) by simply multiplying my result from the integer RNG by 1/((2^32)-1) rather than dividing by (2^32)-1 since it's inefficient.

The way I'm currently going about generating numbers on the interval (0,1) is with a conditional statement like the one below:

float open_open_flt = (closed_open_flt==0) ? closed_open_flt : FLT_MIN; 

Unfortunately, this is rather inefficient since it is control code and I feel like it introduces some bias.

Can anybody suggest an alternative?

like image 205
audiFanatic Avatar asked Jul 30 '13 18:07

audiFanatic


People also ask

Which function generates a number between 0 and 1 at random?

The Math.random() function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range.

What is the best method to generate true random numbers?

To generate “true” random numbers, random number generators gather “entropy,” or seemingly random data from the physical world around them. For random numbers that don't really need to be random, they may just use an algorithm and a seed value.

Does random random () include 0 and 1?

The random() method returns a random floating number between 0 and 1.

How do you get a random number between 0 and 1 in C ++?

Using the rand() function to generate random number between 0 and 1 in C++ The rand() function is used to generate a random number in C++.


2 Answers

You are already there.

The smallest distance between two floats your current generator produces is 1/(2^32).

So, your generator is efectively producing [0,1-1/(2^32)].

1/(2^32) is greater than FLT_MIN.

Thus if you add FLT_MIN to your generator,

float open_open_flt = FLT_MIN + closed_open_flt;

you'll get [FLT_MIN,1-(1/(2^32))+FLT_MIN], which works as a (0,1) generator.

like image 186
PA. Avatar answered Sep 28 '22 15:09

PA.


Since the probability of actually observing 0 probability is very small, and checking if a number is equal to 0 is least expensive (as compared to addition or multiplication), I would regenerate the random number repeatedly until it is not equal to 0.

like image 24
ElKamina Avatar answered Sep 28 '22 17:09

ElKamina