2

I'm generating random numbers in C++11. When I run my code

using namespace std;

static std::mt19937_64 rng;

int main() {
rng.seed(11);

    std::cout << rng() << std::endl;
}

It returns random numbers. However, I would like to restrict this to a range of numbers, say 1-1000. How would I do this, using the new <random> file/library introduced in C++11?

12
  • 3
    use the mod operator % Commented Jul 15, 2013 at 21:04
  • 8
    If you want them uniformly distributed, en.cppreference.com/w/cpp/numeric/random/…. Commented Jul 15, 2013 at 21:05
  • 7
    @andre Nope, the modulus operator doesn't generate a uniform distribution of numbers, check it out: cplusplus.com/reference/cstdlib/rand Commented Jul 15, 2013 at 21:06
  • Try this question -- noting that it's a different language, so not a dup (although those answers would do just fine). Commented Jul 15, 2013 at 21:06
  • % is strictly speaking not correct, to see that, assume the complete range was [0, 100) if you would % 80 random numbers from this range, the result would no longer be uniformly distributed. Commented Jul 15, 2013 at 21:07

1 Answer 1

17

Use std::uniform_int_distribution from <random>.

Example:

#include <random>
#include <iostream>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<int> dis(1, 1000);

    std::cout << dis(gen) << '\n';
}

The <random> header includes a lot of other distributions that you can use. You can check it out here

Sign up to request clarification or add additional context in comments.

9 Comments

+1 for easily accommodating other types of distributions, unlike the thinking process that went into my comment.
Wow, thanks the code and everything!
Also, how would I store this random number as a variable?
@user2581872 I don't get any errors. You might want to make that a separate question.
@user2581872: Call it multiple times: foo = dis(gen); bar = dis(gen);
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.