0

I have old code that predates C++11 and it uses rand() for generating random ints.

However, there is shortcoming in rand(): you can't save and then restore the state of the random device; since there is not an object I can save, nor can I extract the state.

Therefore, I want to refactor to use C++11's solution <random>.

However, I do not want a behaviour change - I hope to get exactly the sequence rand() gives me but with <random>.

Do you guys know whether this is achievable?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
user122049
  • 397
  • 1
  • 11
  • This post maybe helpful: [What difference between rand() and random() functions?](https://stackoverflow.com/questions/18726102/what-difference-between-rand-and-random-functions/18726221#18726221) – hddmss Aug 27 '21 at 04:34
  • 3
    In general, it is not achievable, since the workings of `srand()`/`rand()` themselves are unspecified. This means, among other things, that your program using `srand()` and `rand()` are not guaranteed to give the same sequence of values with different compilers, different implementations of the standard library, or for different target systems. Even if you are using the generators from `` in a way that is deterministic, there is no relationship specified between them and the sequences given by `srand()`/`rand()` - the most you can hope for is similar distributions. – Peter Aug 27 '21 at 04:40

2 Answers2

2

What you want is not possible. The C-style random number generator is implementation-defined. The C++ random engines are all very well specified as to their particular algorithms (except random_device, which varies due to potentially being a more "true" random generator). None of its engines are defined to have the same algorithm as rand.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
2

You can't even assure that you get the same sequence if you use rand() on another compiler. And no, you can't get random to produce the same sequence as whoever's rand() it was you were using. (Thank goodness. rand() is notorious for being one of the worst pseudo-random number generators of all time.)

It is possible for you to restore the state of rand(), simply by using srand() to set the initial state and counting how many times you called rand(). You can later repeat that to bring rand() back to that same state.

But don't use rand()!

Mark Adler
  • 101,978
  • 13
  • 118
  • 158
  • yes if this is compiled on macOS then the crappy output sequence will be always divisible by 7 [Why does rand() % 7 always return 0?](https://stackoverflow.com/q/7866754/995714), [Rand() % 14 only generates the values 6 or 13](https://stackoverflow.com/q/20263187/995714) – phuclv Aug 27 '21 at 04:51