Special simple random number generator

后端 未结 7 2074
一整个雨季
一整个雨季 2020-12-01 08:47

How to create a function, which on every call generates a random integer number? This number must be most random as possible (according to uniform distribution). It is only

相关标签:
7条回答
  • 2020-12-01 09:02

    Linear congruential generators are one of the oldest and simplest methods:

    int seed = 123456789;
    
    int rand()
    {
      seed = (a * seed + c) % m;
      return seed;
    }
    

    Only a few instruction with basic arithmetic operations, that's all you need.

    Mind that this algorithm works fine only if a, c and m are chosen in a particular way!

    To guarantee the longest possible period of this sequence, c and m should be coprime, a − 1 should be divisible by all prime factors of m, and also for 4 if m is divisible by 4.

    Some examples of parameters are shown on Wikipedia: for example ANSI C for some compilers proposes m = 2 ³¹, a = 1103515245 and c = 12345.

    0 讨论(0)
提交回复
热议问题