1

I am using the rand() function in c++ yet i am getting very close numbers every time here is my code`

int pickrandom(){
  time_t t;
  time(&t);
  srand (t);
  return rand();
}

I get numbers like : 13809 13812 13812 13817

  • Because it's just giving back the seed on its first call IIRC, and that seed is your time. Call `rand()` again after the `srand()` call. – Blaze Feb 21 '19 at 10:21
  • 5
    Seed only *once*. – Some programmer dude Feb 21 '19 at 10:21
  • Also, the [pseudo-random generation functionality in the standard C++ library](https://en.cppreference.com/w/cpp/numeric/random) is a lot more than `srand` and `rand`. I suggest you use that instead. – Some programmer dude Feb 21 '19 at 10:28
  • @Blaze -- even if that's true, calling `rand()` again won't fix this problem. The problem comes from the calling `srand` before every call to `rand()`. – Pete Becker Feb 21 '19 at 13:21
  • @PeteBecker those are two separate errors, then. Calling `rand()` just once will still result in those "similar" results when run in somewhat quick succession, at least on my machine. – Blaze Feb 21 '19 at 13:38
  • @Blaze -- a pseudo-random number generator produces the **same** sequence of values when started with the same seed. If the code calls `srand()` with the same seed, calling `rand()` twice or three times or fourteen times won't change that. Those 13812 values are probably from the same seed, and calling `rand()` again doesn't change that. I don't know what you mean by "calling `rand()` just once ... in somewhat quick succession". – Pete Becker Feb 21 '19 at 13:53
  • @PeteBecker I know how a RNG works. Let me explain it this way: If I run `srand(1); printf("%d", rand());`, I get `42`. If I run in with `srand(2);` I get `45`. With `srand(3);` I get `48`. Notice a pattern? If the delta of the result of the first `rand()` directly correlates like that with the parameter of the first `srand` call and OP seeds using the seconds of his system time then the result is exactly as he describes: the first `rand` call yields close results every time the program is executed. That happens even if you seed just once. – Blaze Feb 21 '19 at 14:06
  • I know this problem well because I once had an issue where I scaled a `rand()` result down to [0.0, 1.0] to retrieve a weighted random element from a set and got the exact same result every time - despite seeding *just once* each time, using the system clock. So yes, you should seed just once, but you also shouldn't use the first `rand()` result and expect it to be drastically different if your seed wasn't drastically different. – Blaze Feb 21 '19 at 14:06

1 Answers1

4

You are seeding the random generator on every pickrandom call, which defeats the purpose of seeding. Also, rand is a low-quality generator that has been superseded by the C++11 <random> library – you should use that instead.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416