1

I'm trying to generate a random number that's uniformly distributed between [0,1) and I have tried uniform_real_distribution but I don't know exactly how that works. I have this code below but it keeps generating close to the same numbers every time ~.456

void RandomNumber()
{
srand(time(0));
double number=(double)rand()/((double)RAND_MAX+1);
cout<<"RANDOM NUMBER: "<<number<<endl;
}
John
  • 17
  • 1
  • 1
  • 2
  • Wouldn't it be easier to generate a larger int and divide it? For instance, you could generate a number between 1-1000 and then divide by 1000? – Tas Feb 10 '18 at 00:50
  • 4
    `std::uniform_real_distribution` is indeed what you want to use. Here is a link to documentation and a usage example: http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution If this doesn't sort things out, please post your attempt at using it so we can help you understand. – user4581301 Feb 10 '18 at 00:51
  • Please post a complete but minimal example that readers can copy, paste, compile and run to reproduce the problem. – Cheers and hth. - Alf Feb 10 '18 at 00:55
  • @Tas that's generally not a good way to generate a random number like this. You'll only have 1000 unique values, but there are a lot more that can be represented by a float/double. – Steve Feb 10 '18 at 00:57
  • 1
    srand(0) seeds your random generator - essentially on each call of your function you are "preparing" the basis for your random values the same. Move it outside the function and call it only once (and without the 0 so it takes the current time and gets independant seeds on different runs). rand() is _not_ uniform. – Patrick Artner Feb 10 '18 at 00:57

2 Answers2

6
  1. Don't use rand, it is a poor random number generator

  2. Don't reset the seed every time you call the generator

  3. Use a C++11 one. Clearer to read, portable and simple to maintain

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<> dis(0, 1);//uniform distribution between 0 and 1
    for (int n = 0; n < 10; ++n) {
        std::cout << dis(gen) << ' ';
    }
    
Gabriel
  • 3,564
  • 1
  • 27
  • 49
5

You reset the seed of the random generator every single time you generate a random number, which means if you try to generate numbers repeatedly over a short period of time you will likely get the same results since std::time() is only accurate to a second.

You should just call std::srand() once during the start of the program, or better yet, use a std::uniform_real_distribution. If you are confused about how the <random> library works, take a look at this.

eesiraed
  • 4,626
  • 4
  • 16
  • 34