dongqu3623 2010-11-14 15:20
浏览 63
已采纳

读/ dev / urandom并生成随机整数

I am trying to create a function that generates a random integer out of the bytes I get from /dev/urandom. I am doing this in PHP and it currently looks like:

    public static function getRandomInteger($min, $max)
    {
        // First we need to determine how many bytes we need to construct $min-$max range.
        $difference = $max-$min;
        $bytesNeeded = ceil($difference/256);

        $randomBytes = self::getRandomBytes($bytesNeeded);

        // Let's sum up all bytes.
        $sum = 0;
        for ($a = 0; $a < $bytesNeeded; $a++)
            $sum += ord($randomBytes[$a]);

        // Make sure we don't push the limits.
        $sum = $sum % ($difference);

        return $sum + $min;
    }

Everything works great except that I think it's not calculating the values exactly fair. For example, if you want to have a random value between 0 and 250, it receives one byte and mods it with 250 so the values of 0-6 are more likely to appear than the values of 7-250. What should I do to fix this?

  • 写回答

2条回答 默认 最新

  • dousi9215 2010-11-14 15:34
    关注

    a) If you don't need cryptographically secure random numbers, simply use mt_rand. It will probably suffice for your needs.

    b) If you want to stick with your algorithm: Do some remapping: return round($min + $sum / pow(256, $bytesNeeded) * ($max - $min)).

    c) As you can see, this requires rounding. That will lead to a not perfectly uniform distribution, I think (though I am not sure about this). Probably the best way is to get the random number as a float and then scale it. Though I have no idea how you get a float from /dev/urandom. That's why I stick with mt_rand and lcg_value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口