How random is PHP's shuffle function?

后端 未结 7 1961
眼角桃花
眼角桃花 2020-12-03 21:12

Does anyone know what\'s the randomness of PHP\'s shuffle() function? Does it depend on the operating system? Does it use PHP\'s own seeder?

Is it poss

7条回答
  •  一向
    一向 (楼主)
    2020-12-03 21:54

    shuffle() function is based on the same generator as rand(), which is the system generator based on linear congruential algorithm. This is a fast generator, but with more or less randomness. Since PHP 4.2.0, the random generator is seeded automatically, but you can use srand() function to seed it if you want.

    mtrand() is based on Mersenne Twister algorithm, which is one of the best pseudo-random algorithms available. To shuffle an array using that generator, you'd need to write you own shuffle function. You can look for example at Fisher-Yates algorithm. Writing you own shuffle function will yield to better randomness, but will be slower than the builtin shuffle function.

提交回复
热议问题