I'm trying to generate a random double between -1 and 1, should have 2 significant figures i.e. 0.23, here is what I have so far but it repeats the same number over and over.
1 2 3 4 5 6
double fRand()
{
srand(time(0));
double a = rand() % 201 - 100;
return a / 100.0;
}
I think it won't meet this requirement (without additional rounding): should have 2 significant figures i.e. 0.23
ie. generate one of the 201 possible floating point values.
You do call srand() with current time. If the timer has low resolution and you call fRand() rapidly, then current time remains same on every call.
Same time == same seed => same position in the deterministic sequence from which the rand() picks numbers from.
In other words, calling srand() more than once in your program is the likely cause of repeats.
Overall, the rand() and srand() have been deprecated; scheduled for removal. It is not recommended to use them in new programs. One has to learn the <random> if one needs randomness in the future, so why not start now?
the rand() and srand() have been deprecated; scheduled for removal
I don't think it has been officially deprecated yet, only discouraged.
Note on rand() from the C++17 standard
The other random number generation facilities in this International Standard (29.6) are often preferable to rand, because rand’s underlying algorithm is unspecified. Use of rand therefore continues to be non-portable, with unpredictable and oft-questionable quality and performance.
I don't think these will become deprecated in C++ before they become deprecated in C.
std::random_shuffle() ("An implementation may use the rand function from the standard C library"), where C compatibility was not a concern, was deprecated (C++14) and removed (C++17).