0

I'm using and reusing large number sequences which I (re)generate with rand(). To get different sequences I use srand() with different but known seeds.

How portable is this approach? Will this working over different platforms with different versions of the libc and compilers and CPUs?

Are there safer alternatives to this approach?

Just to clarify: this is not for cryptographic usage.

Patrick B.
  • 11,773
  • 8
  • 58
  • 101

3 Answers3

4

You are guaranteed to get the same sequence of numbers for a particular seed on a particular implementation. You are not guaranteed to get the same sequence for a particular seed across different implementations.

If all you care about is that the sequence is repeatable, you're good. If you care that the sequence is the same across implementations, you're not.

John Bode
  • 119,563
  • 19
  • 122
  • 198
3

This approach is flawed in multiple ways.

  • It makes your application inherently single threaded.

  • C standard doesn't specifying an algorithm for rand, so it can vary between platforms and compilers.

  • Any external (say, GUI) code can by accident call rand, invalidating your sequence. In C++, it gets even worse. Read Compatibility section.

  • Standard rand function is often considered not very good altogether.

For C++, consider using stuff from <random> header, especially some variant of Mersenne Twister.

For C, you should probably look for some libraries implementing MT or other good PRNG.

If you want to implement it yourself, Java Random is both good enough for most cases and easy to implement.

0

See C++14 standard, 26.8.5: C library [c.math]

[...] [ Note: The random number generation (26.5) facilities in this standard are often preferable to rand, because rand’s underlying algorithm is unspecified. Use of rand therefore continues to be nonportable, with unpredictable and oft-questionable quality and performance. — end note ]

So standard states clearly that using rand is not portable. The header provides right away a series of different templates for random number generators, for each the algorithm being dictated and thus being portable. It's then up to you to chose... All but the std::default_random_engine, which is left for the implementation to select again (26.5.5, [10]:

Remark: The choice of engine type named by this typedef is implementation-defined. [...]

Aconcagua
  • 24,880
  • 4
  • 34
  • 59