Why does rand () produce the same value when sowing 1 and UINT_MAX?

Here is the code:

#include <iostream>

int main() {
    srand(1);
    std::cout << rand() << "\n";
    srand(UINT_MAX);
    std::cout << rand() << "\n";
}

This leads to the following conclusion:

16807
16807

Why do these two seeds give the same result? The entire sequence of values ​​that they produce in successive calls rand()is also identical. The range of possible values ​​is too large to be a pure coincidence. It:

  • Randomness of implementation rand()(and if so, I'm curious what it could be)
  • By design (and if so, why?)

(Possibly related: seeds 10, 100, 1000, 10000 and 100000 produce 168070, 1680700, 16807000, 168070000 and 1680700000 respectively.)

+4
source share
5 answers

Lehmer. RNG, , , - , , , .

16807 ( 7) RHG Lehmer, 1988 , -, !

N- ( ^ ):

R(n) = (seed * (16807 ^ n)) mod (2 ^ 31 - 1)

seed = 1, n = 1:

R(1) = 16807 mod (2 ^ 31 - 1) = 16807

seed = 2 ^ 32 - 1:

R(1) =
    (2 ^ 32 - 1) * 16807 ≑ (expressing 2^32 = 2^31 * 2)
    ((2 ^ 31 - 1) * 2 + 1) * 16807 ≑ (distributive law)
    (2 ^ 31 - 1) * 2 * 16807 + 1 * 16807 ≑ (modulo 2^31-1)
    16807

, RHG 2 (2^31-1), 2 (2^32-1).

seed = 2^31.

+3

tl; dr: rand() , .

. :

seed:          1 : 41
seed: 4294967295 : 35
seed:         10 : 71
seed:        100 : 365
seed:       1000 : 3304
seed:      10000 : 32694

rand() . .

( ).

0... 32767, , , , , .

++ . <random> .

+3

. . rand()? .

, UINT_MAX. , 1 UINT_MAX .

rand(),

first_random_number  = (seed * const + another_const)  % third_constant

. .

+2

, , , rand, . , , . , , . .

, ,

, , . , - , , .

0

As indicated here , if the seed is set to 1, the generator is reinitialized to its initial value and returns the same values ​​as before any call to rand or srand.

Also note that two different initializations with the same seed will generate the same sequence of results on subsequent calls to rand.

-3
source

Source: https://habr.com/ru/post/1617260/


All Articles