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 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?