-2

I have to write a c++ program and have a problem only with the following part:

[...] for that purpose, you will need two random integral numbers from uniform distribution on the set {0,1,...,9} (those two numbers have to be generated with equal probability) [...]

I don't know math as good as c++, also I'm not allowed to use c++11. I've written the following simple code, but I doubt if it's correct? :P

//...
srand(time(0));
int first_number = rand() % 10;
int second_number = rand() % 10;
//...

2 Answers2

1

Only call srand once per program, not every time you want a random number. Using the modulus trick for random numbers usually doesn't give an even distribution. So no, the solution is probably not correct.

Neil Kirk
  • 20,002
  • 5
  • 48
  • 79
  • Do you see two calls to srand? Maybe I should buy myself a new pair of better glasses. – Jan Gąser Sep 05 '15 at 04:06
  • @JanGąser I can't tell from your code fragment, but if that is in a function which you call more than once, it would be called multiple times. – Neil Kirk Sep 05 '15 at 04:53
0

It depends on if you need it to be truly uniform, or just very close. Your solution is close but not perfect.

Suppose you're using Microsoft's C++, which has a RAND_MAX of only 32767. Your odds of getting a 0 through 7 are 3277/32768, while your odds of getting an 8 or 9 are only 3276/32768.

There are plenty of questions here on StackOverflow on how to obtain a perfect distribution, such as this one: What is the optimal algorithm for generating an unbiased random integer within a range?

Community
  • 1
  • 1
Mark Ransom
  • 271,357
  • 39
  • 345
  • 578