15

次のような PHP で大きな乱数を生成する方法を探しています。

mt_rand($lower, $upper);

私が見たより近いのはgmp_random () ですが、リムあたりのビット数だけで下限と上限を指定することはできません (これが何であるかはわかりません)。

編集: Axsuuls の回答は、私が望むものにかなり近く、gmp_random に非常に似ているようですが、1 つのシナリオには 1 つの欠陥しかないようです。

次の間の乱数を取得したくないとします。

  • 1225468798745475454898787465154

と:

  • 1225468798745475454898787465200

したがって、関数がBigRandomNumber () と呼ばれる場合:

BigRandomNumber($length = 31);

これは、指定された境界の外にある 9999999999999999999999999999999 を簡単に返すことができます。

長さの値の代わりに最小/最大境界を使用するにはどうすればよいですか?

BigRandomNumber('1225468798745475454898787465154', '1225468798745475454898787465200');

これは、 1225468798745475454898787465 [154 .. 200]の間の乱数を返す必要があります。

参考までに、解決策はこの質問で提供されている機能を利用する必要があると思います。

編集:上記の投稿は削除されました。ここにあります:

function compare($number1, $operator, $number2) {
  $x = bccomp($number1, $number2);

  switch($operator) {
    case '<':
      return -1===$x;
    case '>':
      return 1===$x;
    case '=':
    case '==':
    case '===':
      return 0===$x;
    case '!=':
    case '!==':
    case '<>':
      return 0!==$x;
  }
}
4

14 に答える 14

16

次のことを試してください。

function BigRandomNumber($min, $max) {
  $difference   = bcadd(bcsub($max,$min),1);
  $rand_percent = bcdiv(mt_rand(), mt_getrandmax(), 8); // 0 - 1.0
  return bcadd($min, bcmul($difference, $rand_percent, 8), 0);
}

計算は次のとおりです。最小値と最大値の差にランダムなパーセンテージを掛け、最小値に加算します(intに丸めます)。

于 2009-10-01T15:31:09.403 に答える
6

本当に知っておく必要があるのは、相対的なギャップです。小さい場合は、0 から最大ギャップまでの数値を生成し、それに最小値を追加できます。

于 2009-10-03T03:58:16.173 に答える
2

これにより、巨大な乱数のゼロが増え、巨大な乱数の長さを指定することもできます(巨大な乱数を0から始めることはできますか?そうでない場合は、簡単に実装できます)

<?php

$randNumberLength = 1000;  // length of your giant random number
$randNumber = NULL;

for ($i = 0; $i < $randNumberLength; $i++) {
    $randNumber .= rand(0, 9);  // add random number to growing giant random number

}

echo $randNumber;

?>

幸運を!

于 2009-09-25T22:51:41.863 に答える
1

できることは、いくつかの小さな乱数を作成し、それらを組み合わせることです。ただし、実際に必要なサイズについてはわかりません。

于 2009-09-25T22:26:52.990 に答える
0
/* Inputs: 
 * min - GMP number or string: lower bound
 * max - GMP number or string: upper bound
 * limiter - GMP number or string: how much randomness to use.
 *  this value is quite obscure (see `gmp_random`, but the default
 *  supplies several hundred bits of randomness, 
 *  which is probably enough.
 * Output: A random number between min (inclusive) and max (exclusive).
*/
function BigRandomNumber($min, $max, $limiter = 20) {
  $range = gmp_sub($max, $min);
  $random = gmp_random();
  $random = gmp_mod($random, $range);
  $random = gmp_add($min, $random);
  return $random;
}

これは、rand_range($min, $max) = $min + rand() % ($max - $min)任意精度の算術に変換される古典的な式です。2の累乗でない場合、ある程度のバイアスを示す可能性がありますが、バイアス$max - $minのサイズと比較してランダム性のビット数が十分に多い場合は、$max - $min無視できるようになります。

于 2009-10-03T10:49:18.310 に答える
0
$lower = gmp_com("1225468798745475454898787465154");
$upper = gmp_com("1225468798745475454898787465200");

$range_size = gmp_sub($upper, $lower);

$rand = gmp_random(31);
$rand = gmp_mod($rand, $range_size);

$result = gmp_add($rand, $lower);

完全にテストされていません:-)

于 2009-10-01T15:36:52.217 に答える
0

これはうまくいくかもしれません:

  • 私のマシンでは最大ランド数が2147483647であるため、数値を9個以下の配列(「残り」)... 9文字に分割します。
  • 「9個以下の数字配列ブロック」ごとに、乱数を作成します。
  • 配列を内破すると、使用可能な乱数が得られます。

アイデアを説明するコード例 (注意: コードは元に戻されています)

function BigRandomNumber($min,$max) {
// Notice: Will only work when both numbers have same length.
echo (strlen($min) !== strlen($max)) ? "Error: Min and Max numbers must have same length" : NULL;
$min_arr = str_split($min);
$max_arr = str_split($max);
// TODO: This loop needs to operate on 9 chars ($i will increment by $i+9)
for($i=0; $i<=count($max_arr); $i++) {
    if($i == 0) {
        // First number: >=first($min) and <=first($max).
        $new_arr[$i] = rand( $min_arr[0], $max_arr[0]);
    } else if($i == count($max_arr)) {
        // Last number <= $max .. not entirely correct, feel free to correct it.
        $new_arr[$i] = rand(0, substr($max,-1));
    } else {
        $new_arr[$i] = rand(0,9);
    }
}
return implode($new_arr);
}
于 2009-10-03T17:01:29.407 に答える
0

random('9999999999') は理論的には 1 を返す可能性があるため、「n」個のランダムな文字を生成することは実際にはオプションではありません...

これは非常に単純な関数です:

function bcrand($max) { 
    return bcmul($max, (string)mt_rand() / mt_getrandmax() ); 
}

Nビットの乱数を返さないことに注意してください。スケールを調整するだけです

于 2013-03-09T02:25:58.493 に答える
0

これはあなたのために働くかもしれません。(なぜそれが必要なのかわからないので、それを行うのが最善の方法ではないかもしれませんが、要件に合うはずです):

<?php
function bigRandomNumber($min, $max)
{
 // check input first
    if ($max < $min) { return false; }
    // Find max & min length of the number
    $lenMin = strlen ($min);
    $lenMax = strlen ($max);

    // Generate a random length for the random number
    $randLen = $lenMin + mt_rand(0, $lenMax - $lenMin);
    /* Generate the random number digit by digit, 
       comparing it with the min and max values */
 $b_inRange = false;
    for ($i = 0; $i < $randLen; $i++)
 {
  $randDigit = mt_rand(0,9);

  /* As soon as we are sure that the number will stay 
          in range, we can stop comparing it to min and max */
  if (!$b_inRange)
  {
   $tempRand = $rand . $randDigit;
   $tempMin = substr($min, 0, $i+1);
   $tempMax = substr($max, 0, $i+1);
   // Make sure that the temporary random number is in range
   if ($tempRand < $tempMin || $tempRand > $tempMax)
   {
    $lastDigitMin = substr($tempMin, -1);
    $lastDigitMax = substr($tempMax, -1);
    $tempRand = $rand . @mt_rand($lastDigitMin, $lastDigitMax);
   }
   /* Check if $tempRand is equal to the min or to the max value. 
               If it is not equal, then we know it will stay in range */
   if ($tempRand > $tempMin && $tempRand < $tempMax)
   {
    $b_inRange = true;
   }
  }
  else
  {
   $tempRand = $rand . $randDigit;
  }
  $rand = $tempRand;  
 }
 return $rand;
}

数回試してみましたが、問題なく動作するようです。必要に応じて最適化します。アイデアは、乱数のランダムな長さを許容範囲内に収めることから始めることです。次に、連結してその長さまで乱数を 1 つずつ生成します。範囲内にない場合は、範囲内の新しい乱数を生成して連結します。

文字列関数を利用するために、PHP が文字列を数値に変換するという事実を利用します。もちろん、これは mt_rand に対して警告を生成しますが、数値のみを使用するため、これを抑制しても安全です。

さて、そもそもなぜこれが必要なのか、非常に興味があります。

于 2009-10-03T08:04:25.807 に答える
0

テスト済みで動作します

<?php 

$min = "1225468798745475454898787465154";
$max = "1225468798745475454898787465200";

$bigRandNum = bigRandomNumber($min,$max);
echo "The Big Random Number is: ".$bigRandNum."<br />";

function bigRandomNumber($min,$max) {
    // take the max number length
    $number_length = strlen($max);

    // Set the counter
    $i = 1;

    // Find the base and the min and max ranges
    // Loop through the min to find the base number
    while ($i <= $number_length) {
        $sub_string = substr($min, 0, $i);

        // format pattern
        $format_pattern = '/'.$sub_string.'/';
        if (!preg_match($format_pattern, $max)) {
            $base = $sub_string;

            // Set the min and max ranges
            $minRange = substr($min, ($i - 1), $number_length);
            $maxRange = substr($max, ($i - 1), $number_length);

            // End while loop, we found the base
            $i = $number_length;
        }
        $i++;
    }
    // find a random number with the min and max range
    $rand = rand($minRange, $maxRange);

    // add the base number to the random number
    $randWithBase = $base.$rand;

    return $randWithBase;
}

?>
于 2009-10-05T12:54:31.830 に答える
-1

あなたの床とそれに範囲内のあなたの乱数を取りなさい。

1225468798745475454898787465154 + rand(0, 6)
于 2009-10-01T15:43:54.780 に答える
-1

擬似コードは次のとおりです。


// generate a random number between N1 and N2

rangesize = N2 - N1 + 1
randlen = length(rangesize) + 4 // the 4 is to get more digits to reduce bias
temp = BigRandomNumber(randlen) // generate random number, "randlen" digits long
temp = temp mod rangesize
output N1 + temp

ノート:

  • ここでのすべての算術演算(2行目を除く)は任意精度でなければなりません。これにはbcmathライブラリを使用します
  • 2行目の「長さ」は桁数であるため、1025の「長さ」は4になります。
于 2009-10-03T03:39:36.157 に答える