I need to generate a high number of random integers in varying ranges [0, N[ where N is a small positive integer N < 1000. I thought that using a uniform_real_distribution and multiplying by N would do it, but I ran into a problem: Very (very very) rarely, it yields N, which is out of bounds.
#include <random>
std::default_random_engine generator;
std::uniform_real_distribution<float> Udistribution(0.0f, 1.0f); // [0, 1)
int N = 5;
int R;
R = (int) (Udistribution(generator) * (float)N);
// R = N sometimes !!!
// Also happens when using floor instead of casting to int.
I thought the reason could be that casting N to a float could increase it just enough so that if the random float is something like .9999999999f, their product could reach over 1. But it happened with N = 5 and N = 10, both being perfectly represented in floats. What could be the reason then ? the float product operation's approximation ?
(I'm not using uniform_int_distribution because N is different each time and I though it would be cheaper this way, yeah I know benchmarking is the way. Just asking this out of curiosity.)