5

I am working on a C++ assignment for my class, and we have to use rand () with a seed of 99 to produce a set of values. However, my problem is that when I try to create a value within our parameters, the number is different than what the instructor provided us for a definite first number. The code is shown below:

 int lottoNumber; srand (RANDOM_NUMBER_SEED); do { lottoNumber = rand (); } while (lottoNumber > 25 || lottoNumber < 1); cout << lottoNumber << endl; 

The value produced from this is 13, while the number expected to be produced is 2. Any help as to why this is different would be great, thanks!

1
  • You can probably get rid of the loop altogether, and just use lottoNumber = rand() % 25 + 1;. It may not be perfectly distributed but it should do for anything other than a real lottery but if it were a real lottery, I suspect government regulations would require something better than a PRNG :-) Commented Feb 11, 2017 at 1:06

3 Answers 3

9

Algorithm used by rand() is implementation-defined.

Which means that it might be different on different compilers and compiler versions.

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

Comments

5

Your instructor is hallucinating. This is a pseudo-random number generator. Just because the properties of such a generator tend to produce the same results given the same seed, on any particular invocation of a program, doesn't mean that this behaviour is in any way guaranteed, or that the same property should be expected to apply in general forever.

If you want a deterministic sequence, do not use a random number generator!!!

13 Comments

The rand() random number generator is typically entirely deterministic, depending on the value set by srand(), In fact, this is one of its few useful features.
@NeilButterworth: The OP has discovered, in fact, and quite rightly, that this is not true.
Deterministic != All implementations produce same results
@NeilButterworth: No, that's precisely what it means.
An instance of a PRNG may be deterministic given the same seed (though it's by no means required in general, the ISO C standard mandates this). The standard does not require determinism across all implementations. It may be the educator and student are using different implementations.
|
4

rand() is implementation dependent, from cppreference.com std::rand:

There are no guarantees as to the quality of the random sequence produced.

You might want to use something more like std::mt19937

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.