mardi 19 mai 2020

vim rand() is not deterministic. Is this expected?

According to :help rand(),

rand([{expr}])

        Return a pseudo-random Number generated with an xoshiro128**
        algorithm using seed {expr}. The returned number is 32 bits,
        also on 64 bits systems, for consistency.
        {expr} can be initialized by srand() and will be updated by
        rand(). If {expr} is omitted, an internal seed value is used
        and updated.
        
        Examples:
         :echo rand()
         :let seed = srand()
         :echo rand(seed)
         :echo rand(seed) % 16 " random number 0 - 15

It doesn't explain how a seed is changed every time rand() is called, but I expected it to be deterministically altered because

  1. C++'s std::rand() does so,

  2. and Wikipedia says

A pseudorandom number generator (PRNG), also known as a deterministic random bit generator (DRBG), is an algorithm...

However, in the code below, the value of a is deterministic but the values of b are not deterministic; they take different values when you restart the script.

let seed = srand(0)
let a = rand(seed)
let b = rand()
echo [a, b]

let seed = [0, 1, 2, 3]
let a = rand(seed)
let b = rand()
echo [a, b]

Is this an expected behavior? I think the behavior contradicts the documentation.




Aucun commentaire:

Enregistrer un commentaire