一千萬個為什麽

搜索

為什麽rand()在最小值和最大值為正值時返回負值?

我有一段簡單的PHP代碼,需要創建一個隨機數字。但是,即使輸入總是正數,它有時也會返回負輸出。

這是我的調試代碼:

$debt = rand($this->gdp * 0.02, $this->gdp * 0.17);
echo "
GDP: ".$this->gdp." rand(".$this->gdp * 0.02." , ".$this->gdp * 0.17.") = ".$debt."

";

以下是一個輸出示例:

GDP: 219254674605 rand(4385093492.1 , 37273294682.85) = 75276999

GDP: 345015694865 rand(6900313897.3 , 58652668127.05) = -1636353016

GDP: 90445390920 rand(1808907818.4 , 15375716456.4) = -165604705

GDP: 3412849650 rand(68256993 , 580184440.5) = 347516196

GDP: 2939111315 rand(58782226.3 , 499648923.55) = 119181875

GDP: 26369065 rand(527381.3 , 4482741.05) = 3632416

GDP: 215838135 rand(4316762.7 , 36692482.95) = 28784811

GDP: 511763530 rand(10235270.6 , 86999800.1) = 39954394

GDP: 42416245 rand(848324.9 , 7210761.65) = 3974882

GDP: 75090235 rand(1501804.7 , 12765339.95) = 5201966

那麽,為什麽兩個正數的 rand()會給出負的回報呢?

任何幫助將非常感激!

最佳答案

因為你在參數中看到一個整數溢出。

According to the rand() documentation it takes two int values as arguments. On a 32-bit machine those are 32 bit as well (at least for PHP). So when you pass arguments larger than 231 − 1 they overflow and start at −231 again.

顯然,如果你需要更大的值,你必須自己編寫代碼。雖然只是從兩個32位數字創建64位數字按預期工作,但不能簡單地使用最大值進行模運算,因為這會偏離分布。要獲得一個良好的實現方法,請參閱,了解如何生成0到某個上限之間的均勻分布的隨機整數/util/Random.html#nextInt%28int%29“rel =”noreferrer“> java.util.Random.nextInt(int),並相應地調整為64位整數。

mt_rand() while usually a nice choice for random numbers because it uses MT19937 instead of a poor LCG, doesn't help here either as its arguments are ints as well.


Another option you might want to consider if you don't require every possible value to be picked eventually:

  • Generate a random floating-point value between 0 and 1 by calling

    $rnd = mt_rand()/(double)mt_getrandmax()
    
  • Determine the range of numbers you need:

    $min = $this->gdp * 0.02;
    $max = $this->gdp * 0.17;
    $range = $max - $min;
    
  • Multiply this by the previously-obtained random floating-point value and add the minimum:

    $value = $min + $range * $rnd
    
  • Now you have a random value between your chosen boundaries. It's approximately uniformly distributed, although there are discrete steps between adjacent random numbers as you are stretching 32 bits of randomness over a larger number of bits. If that's no problem for you, go ahead, though.

轉載註明原文: 為什麽rand()在最小值和最大值為正值時返回負值?