dongsimang4036 2013-05-10 08:01 采纳率: 100%
浏览 109
已采纳

在PHP中使用OpenSSL随机获取负数

I'm messing around with some code to make a strong pseudo-random number generator using PHP. So far, I have the following.

function strongRand($bytes, $min, $max)
{
    if(function_exists('openssl_random_pseudo_bytes'))
    {
        $strong = true;
        $n = 0;

        do{
            $n = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes, $strong)));
        }
        while($n < $min || $n > $max);

        return $n;
    }
    else{
        return mt_rand($min, $max);
    }
}

This is almost perfect for me—except that all of the numbers that I generate with openssl_random_pseudo_bytes are positive. Ideally, I'd like to generate numbers from -x to +y. I have thought about maybe adding a another PRNG call to decide if a number should be positive or negative, but I'm not sure if that's the best way to go.

  • 写回答

2条回答 默认 最新

  • douyan8961 2013-05-10 08:58
    关注

    You could simply add another random function, we'll use rand(0,1) this will generate 0 or 1, if it's 1 $status = 1 if it's 0 $status = -1. When we return the value we do multiplication by $status:

    function strongRand($bytes, $min, $max)
    {
        $status = mt_rand(0,1) === 1 ? 1:-1;
    
        if(function_exists('openssl_random_pseudo_bytes'))
        {
            $strong = true;
            $n = 0;
    
            do{
                $n = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes, $strong)));
            }
            while($n < $min || $n > $max);
    
            return $n * $status;
        }
        else{
            return mt_rand($min, $max) * $status;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建