-1

I found this formula and thought it was a good one to use for getting a randomly generated number between 0 and 1. However, I need to compare the randomly generated number to other numbers. How do I store for use in if comparison statements.

double r() {
    random_device rd;
    mt19937 gen(rd());
    uniform_real_distribution<> dis(0, 1);
    cout << "dis gen is " << dis(gen) << endl;

//    cout << '\n';

    return 0;
}
  • 6
    I suggest you pick up a [good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) on C++ and start reading. – Captain Obvlious Jun 19 '14 at 04:01

1 Answers1

0

You can just store the value returned by dis(gen) in a variable:

auto value = dis(gen);

dis(gen) generates a value with generator gen according to the distribution dis. In this case, it returns you a random real number uniformly distributed between 0 and 1.

If you want to be explicit about the returned type (instead of using auto to deduce the type automatically):

decltype(dis)::result_type value = dis(gen);

Or in full:

uniform_real_distribution<>::result_type value = dis(gen);

This just means that you'll need to update two lines if you change the distribution.

If you want to be super explicit and give the type that result_type will be (which is in this case the default type double):

double value = dis(gen);
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • Can you explain what that means? value is the variable now? dis(gen) is just the random variable? I didn't follow the way the original was working. – user3753931 Jun 19 '14 at 04:00
  • They'll have to fix their return statement first though. – Captain Obvlious Jun 19 '14 at 04:00
  • `uniform_real_distribution` produces `double`s by default. I think it's bad style to use `auto` here because you can't tell what the type is. – Brian Bi Jun 19 '14 at 04:01
  • 1
    @Brian Well you can never tell what the type is when you use `auto`. I'd suggest this is a good use of `auto`, because I don't really care what the type is. I just know it's a random real value between 0 and 1, and I can see that from the code. – Joseph Mansfield Jun 19 '14 at 04:05
  • @user3753931 Let me know if this helps, but this is really very simple. You're taking the value returned by `dis(gen)` and storing it in the variable `value`. Just like `int x = 5;` stores `5` in `x`. – Joseph Mansfield Jun 19 '14 at 04:06
  • @JosephMansfield Well, sometimes you can tell. I mostly use `auto` to avoid writing out iterator types, and it's fairly clear because you know what type the container is. In this case here if you need to know the type of `value` at some later point you're going to have to look it up, so you may as well look it up right away and put it in the declaration. Just my two cents – Brian Bi Jun 19 '14 at 04:14