PHP Velho Oeste 2024

mt_rand

(PHP 4, PHP 5, PHP 7)

mt_rand향상된 난수를 생성

설명

int mt_rand ( void )
int mt_rand ( int $min , int $max )

사용해 온 libc들의 많은 난수 생성기는 이상하거나, 특성을 알 수 없거나, 느렸습니다. 기본적으로, PHP는 rand() 함수에서 libc 난수 생성기를 이용합니다. mt_rand()는 이를 대체합니다. » Mersenne Twister를 사용하는 확실한 특성을 가진 난수 생성기를 이용합니다. 이것은 평균적인 libc 제공의 난수 생성기에 비해 4배 정도 빠릅니다.

선택적인 min, max 인수 없이 호출하면, mt_rand()는 0과 mt_getrandmax() 사이의 모조 난수를 반환합니다. 예를 들어, 5와 15(포함)사이의 난수를 원할 경우에는, mt_rand(5, 15)로 사용합니다.

Note: PHP 4.2.0부터 srand()mt_srand()를 이용한 난수값 생성기 초기화를 할 필요가 없습니다. 자동적으로 이루어집니다.

인수

min

선택적인 반환할 최소값 (기본값: 0)

max

선택적인 반환할 최대값 (기본값: mt_getrandmax())

반환값

min(또는 0)과 max(또는 mt_getrandmax(), 포함) 사이의 임의 정수값

변경점

버전 설명
3.0.7부터 3.0.7 이전 버전에서 max의 의미는 range였습니다. 이 버전에서 위의 짧은 예제처럼 5와 15 사이의 난수를 얻으려면 rand (5,11)을 사용해야 합니다.

예제

Example #1 mt_rand() 예제

<?php
echo mt_rand() . "\n";
echo 
mt_rand() . "\n";

echo 
mt_rand(515);
?>

위 예제의 출력 예시:

1604716014
1478613278
6

참고

add a note add a note

User Contributed Notes 3 notes

up
13
Pawe Krawczyk
10 years ago
To reiterate the message about *not* using mt_rand() for anything security related, here's a new tool that has been just posted that recovers the seed value given a single mt_rand() output:

http://www.openwall.com/php_mt_seed/README
up
7
greald at ghvernuft dot nl
1 year ago
To see some systematic deviations from a universal distribution run:

<?php
$alfabet
= str_split('ADHKLMNPSTUWX');
$countalfabet = count($alfabet)-1;
$code = array_fill_keys($alfabet, 0);
for (
$L=0; $L<80*$countalfabet; $L++)
{
 
$lettr = floor(mt_rand ( 0, $countalfabet ));
 
$code[$alfabet[$lettr]]++;
}

foreach(
$code as $L => $Freq)
{
  for(
$F=0; $F<$Freq; $F++)
  {
    echo
$L;
  }
  echo
"\n<br/>";
}
?>
To Top