3

I'm working on a mobile game, and I needed to create a possibility to play the same level in an absolutely same way. This sounded easy because I knew about a seed for a random generator, which should be the same for this purpose.

The problem arised later, when I used std::mt19937 together with std::uniform_int_distribution as it was in many tutorials. As it was noticed in another question here , random number distributions aren't consistent between platforms, while the engine is consistent (how can it be differenent, if it is based on a mathematical algorithm?).

I didn't pay much attention at this problem and just used std::mt19937 without a distribution.

Is it a correct way of usage, if there is no particular requirements on number distribution?

Nikita Smirnov
  • 813
  • 8
  • 17
  • 2
    You can always code your own distribution, or an entire pseudo-random generator from scratch, that would be consistent across your platforms. For something as meaningless as a mobile game, I doubt that the mathematical qualities of pseudo-random number generation are very important. – Sam Varshavchik Aug 14 '19 at 12:19
  • @SamVarshavchik thanks, I agree with you that one more mobile game with not big ranges of required numbers doesn't need high mathematical quality. – Nikita Smirnov Aug 14 '19 at 12:24
  • related/maybe dupe: https://stackoverflow.com/q/38367976/4342498 – NathanOliver Aug 14 '19 at 12:27

2 Answers2

6

std::mt19937 produces uniform random numbers in the range [0, 232-1]. It implements the Mersenne Twister alrogithm and is guaranteed to provide reproducible results across implementations.

If you need a different range, you need to somehow reduce [0, 232-1] to your desired range. std::uniform_int_distribution is a convenience tool for doing that (but provides no guarantee of portability across implementations).

rustyx
  • 80,671
  • 25
  • 200
  • 267
4

The random number generator std::mt19937 will generate the same values for any platform, but alas the standard allows std::uniform_int_distribution to be flexible.

So you need to do the transformation yourself alas.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    @UmNyobe: http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/ARTICLES/mt.pdf for the generator along with the standard for the specification of the implementation. For `std::uniform_int_distribution` see the standard again; the transformation function is not specified. https://en.cppreference.com/w/ is an adequate proxy for the standard, and it's free. – Bathsheba Aug 14 '19 at 12:48
  • The paper mentioned by @Bathsheba specifies the state transitions. It does not specify the seeding used in the C++ Standard. – user515430 Aug 14 '19 at 15:10