更好的随机生成PHP [英] Better Random Generating PHP

查看:98
本文介绍了更好的随机生成PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,仅使用rand()是可以预测的,如果您知道自己在做什么,并且可以访问服务器.

I know that just using rand() is predictable, if you know what you're doing, and have access to the server.

我有一个高度项目,取决于选择一个尽可能不可预测的随机数.因此,我正在寻找可以生成更好随机数的其他内置函数或用户函数的建议.

I have a project that is highly dependent upon choosing a random number that is as unpredictable as possible. So I'm looking for suggestions, either other built-in functions or user functions, that can generate a better random number.

我用它来做一些测试:

$i = 0;

while($i < 10000){
    $rand = rand(0, 100);

    if(!isset($array[$rand])){
        $array[$rand] = 1;
    } else {
        $array[$rand]++;
    }

    sort($array);
    $i++;
}

我发现结果是均匀分布的,每个数字生成的次数有一个奇怪的规律.

I found the results to be evenly distributed, and there is an odd pattern to the number of times each number is generated.

推荐答案

添加,相乘或截断不良的随机源将给您不良的随机结果.有关说明,请参见随机性和随机数简介.

Adding, multiplying, or truncating a poor random source will give you a poor random result. See Introduction to Randomness and Random Numbers for an explanation.

您对PHP rand()函数是正确的.请参见统计分析上的第二个图,以获取引人注目的插图. (第一个数字引人注目,但这是斯科特·亚当斯(Scott Adams)绘制的,未使用rand()绘制.)

You're right about PHP rand() function. See the second figure on Statistical Analysis for a striking illustration. (The first figure is striking, but it's been drawn by Scott Adams, not plotted with rand()).

一种解决方案是使用真正的随机生成器,例如 random.org .另一个,如果您使用的是Linux/BSD/etc.是使用/dev/random .如果随机性是关键任务,则必须使用硬件随机生成器.

One solution is to use a true random generator such as random.org. Another, if you're on Linux/BSD/etc. is to use /dev/random. If the randomness is mission critical, you will have to use a hardware random generator.

这篇关于更好的随机生成PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆