After noticing that the rand() function produced the same output of 41 each time, I seeded the generator using srand(time(0)). That solved the problem of the recurring output but now it's giving me constantly increasing numbers. (I.E. 245, 248, 250, 253, 255, 256). I can understand that it is increasing because of the influence by the system time but is this normal?
Here is my program:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int number;
srand(time(0));
cout << rand() % 1000;
return 0;
}
I am running this repeatedly and not in a loop. Outputs of multiple trials: 285 295 305 311 325 334 344 354 355
C++ rand() from MS uses the simplest random generator Linear congruential generator
This is the code for it:
int __cdecl rand (
void
)
{
_ptiddata ptd = _getptd();
return( ((ptd->_holdrand = ptd->_holdrand * 214013L
+ 2531011L) >> 16) & 0x7fff );
}
So whenever you seed your function you just set the first value (which obviously increases just by some units from time to time if you run your program fast)
Now if you plug in your math equation of the rand() a value x+a where x is the value with which your function was called last time and a is the variation of your time since that call you will notice:
((x+a) * 214013 + 2531011) >> 16 = (x*214013+2531011 + a*214013) >> 16
Since you run your program very fast. Your a varies between 0 and 5 sec let's say. Then your a*214013 has a max value of 1070065 now when you right shift this number by 16 bits you end up with 16 in decimal and this is approximately how much your new output differs from your previous one (I say approximately because you can not say that (x*214013+2531011 + a*214013) >> 16 = (x*214013+2531011 >> 16) + (a*214013 >> 16) because of the carries)
This bug comes up about once a week here:
If you call srand() every time before you call rand(), then you're not getting random numbers at all, you're getting a hash function of the time. Call srand() ONCE, AND ONLY ONCE, outside the loop, preferably at the very start of your program, then call rand() as many times as needed to get values.
There's no such thing as generating "one random number". If you need random numbers over a series of program invocations, you have no choice but to generate those random numbers outside the program. One way to do that is to read from /dev/urandom (on Linux) or use CryptGenRandom (on Windows). Another option is to use hardware, or a service like random.org.
It doesn't matter how good a generator you have--if you seed every call, you're not getting random numbers, you're getting a hash function of the seed value. If your seed value changes fast enough, and the hash function is very good, that might be good enough--but it's still not using the RNG algorithm at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With