В PHP, как я генерирую большое псевдослучайное число?

Короткий ответ, не волнуйтесь об использовании идентификаторов asp.net. В asp.net можно добавить собственный атрибут к тегу:

<asp:TexBox ID="myTBox" runat="server" MyCustomAttr="foo" />

Затем в jQuery можно обратиться к этому элементу через:

$("input[MyCustomAttr='foo']")

я делаю это все время с jQuery. Надежда это помогает.

15
задан Community 23 May 2017 в 12:34
поделиться

11 ответов

Попробуйте следующее:

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);
}

Математика следующая: умножьте разницу между минимумом и максимумом на случайный процент и прибавьте к минимуму (с округлением до целого числа).

16
ответ дан 1 December 2019 в 03:14
поделиться

Это даст вам больше нулей в вашем гигантском случайном числе, и вы также можете указать длину гигантского случайного числа (можно ваше гигантское случайное число начинается с 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;

?>

Удачи!

2
ответ дан 1 December 2019 в 03:14
поделиться

Что вы можете сделать, так это создать несколько меньших случайных чисел и объединить их. Не уверен, какой размер вам нужен на самом деле.

1
ответ дан 1 December 2019 в 03:14
поделиться

Что вам действительно нужно знать, так это относительный разрыв; если он маленький, вы можете сгенерировать число от 0 до максимального разрыва, а затем добавить к нему минимум.

6
ответ дан 1 December 2019 в 03:14
поделиться
$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);

Полностью не проверено: -)

0
ответ дан 1 December 2019 в 03:14
поделиться

This might work for you. (I am not sure why you need it, so it might not be the best way to do it, but it should fit your requirements):

<?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;
}

I tried a couple times and it looks like it works OK. Optimize if needed. The idea is to start by figuring out a random length for your random number that would put it in the acceptable range. Then generate random digits one by one up to that length by concatenating. If it is not in range, generate a new random digit in range and concatenate.

I use the fact that PHP will convert a string to a number to take advantage of the string functions. Of course this generates a warning for mt_rand, but as we use only numbers, it should be safe to suppress it.

Now, I have to say that I am quite curious as to why you need this in the first place.

0
ответ дан 1 December 2019 в 03:14
поделиться
/* 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;
}

This is just the classic formula rand_range($min, $max) = $min + rand() % ($max - $min) translated to arbitrary-precision arithmetic. It can exhibit a certain amount of bias if $max - $min isn't a power of two, but if the number of bits of randomness is high enough compared to the size of $max - $min the bias becomes negligible.

0
ответ дан 1 December 2019 в 03:14
поделиться

Возьмите ваш этаж и ваше случайное число в диапазоне от него.

1225468798745475454898787465154 + rand(0, 6)
-1
ответ дан 1 December 2019 в 03:14
поделиться

Вот псевдокод:


// 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

Примечания:

  • вся арифметика здесь (кроме второй строки) должна иметь произвольную точность: используйте для этого библиотеку bcmath
  • во второй строке , «длина» - это количество цифр, поэтому «длина» 1025 будет 4
-1
ответ дан 1 December 2019 в 03:14
поделиться

Это может сработать:

  • Разделить число на массив с 9 числами или меньше («остальное») ... 9 символов, потому что максимальное число случайных чисел на моей машине составляет 2147483647.
  • Для каждого «блока массива из 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);
}
0
ответ дан 1 December 2019 в 03:14
поделиться

Протестировано и работает

<?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;
}

?>
0
ответ дан 1 December 2019 в 03:14
поделиться
Другие вопросы по тегам:

Похожие вопросы: