PHP Doku:: Erzeugt einen zufälligen Integerwert - function.rand.html

Verlauf / Chronik / History: (31) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzMathematische ErweiterungenMathematische FunktionenMathematische Funktionenrand

Ein Service von Reinhard Neidl - Webprogrammierung.

Mathematische Funktionen

<<rad2deg

round>>

rand

(PHP 4, PHP 5)

randErzeugt einen zufälligen Integerwert

Beschreibung

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

Liefert eine Pseudozufallszahl zwischen min und max (inklusive), oder zwischen 0 und get_randmax() falls keine Parameter angegeben wurden. Wenn Sie z.B. einen Zufallswert zwischen 5 und 15 benötigen so wäre der Aufruf dafür rand(5, 15).

Hinweis: Auf manchen Plattformen (Windows z.B.) ist get_randmax() nur 32768. Wenn sie einen größeren Wertebereich benötigen sollten, so können Sie entweder einen größeren max-Wert übergeben oder besser die mt_rand()-Funktion anstelle von rand() einsetzen.

Hinweis: Seit PHP 4.2.0 besteht keine Notwendigkeit mehr, den Zufallsgenerator für Zahlen mit srand() oder mt_srand() zu füttern, das geschieht nun automatisch.

Parameter-Liste

min

Der niedrigste zurückzugebende Wert (Vorgabe: 0)

max

Der höchste zurückzugebende Wert (Vorgabe: get_randmax())

Rückgabewerte

Ein Pseudozufallswert zwischen min (oder 0) und max (oder get_randmax(), inklusive).

Changelog

Version Beschreibung
Seit 3.0.7 In Versionen vor 3.0.7 war die Bedeutung von max statt dessen range. Um in diesen Versionen das gleiche Ergebnis zu erzielen muss im folgenden Beispiel rand (5, 11) benutzt werden um eine Zufallszahl zwischen 5 und 15 zu erhalten.

Beispiele

Beispiel #1 rand() example

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

echo 
rand(515);
?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

7771
22264
11

Siehe auch

  • srand() - Anfangswert für Zufallsgenerator festlegen
  • getrandmax() - Liefert die maximale Zufallszahl
  • mt_rand() - Erzeugt "bessere" Zufallszahlen


37 BenutzerBeiträge:
- Beiträge aktualisieren...
Jesse
22.12.2010 8:13
I had to come up with a quick way to get a random row from a table, and came up with the following:

<?php
$query
= "SELECT `id` FROM [TABLE]";
$result = mysql_query($query, $link);
$num = mysql_num_rows($result);
if (
$num > 0) {
   
// Array the ID's...
   
$id_array = array();
    while (
$row = mysql_fetch_assoc($result)) {
       
$id_array []=$row["id"];
    }
   
$query = "SELECT * FROM [TABLE] WHERE `id`=".$id_array[rand(0, (count($id_array)-1))];
   
$result = mysql_query($query, $link);
   
$row = mysql_fetch_assoc($result);
   
// ...
}
?>
Alireza Eliaderani
10.09.2010 23:18
Random integers with normal distribution,
it's not scientifically approved, but worked for me.

<?php
/*
* @param float  $mean, desired average
* @param number $sd, number of items in array
* @param number $min, minimum desired random number
* @param number $max, maximum desired random number
* @return array
*/
function array_distribute($mean,$sd,$min,$max){
   
$result = array();
   
$total_mean = intval($mean*$sd);
    while(
$sd>1){
       
$allowed_max = $total_mean - $sd - $min;
       
$allowed_min = intval($total_mean/$sd);
       
$random = mt_rand(max($min,$allowed_min),min($max,$allowed_max));
       
$result[]=$random;
       
$sd--;
       
$total_mean-=$random;
    }
   
$result[] = $total_mean;
    return
$result;
}
?>
liveonaware [at] gmail [dot] com
1.06.2010 5:16
<?php
//To Pull 7 Unique Random Values Out Of AlphaNumeric

//removed number 0, capital o, number 1 and small L
//Total: keys = 32, elements = 33
$characters = array(
"A","B","C","D","E","F","G","H","J","K","L","M",
"N","P","Q","R","S","T","U","V","W","X","Y","Z",
"1","2","3","4","5","6","7","8","9");

//make an "empty container" or array for our keys
$keys = array();

//first count of $keys is empty so "1", remaining count is 1-6 = total 7 times
while(count($keys) < 7) {
   
//"0" because we use this to FIND ARRAY KEYS which has a 0 value
    //"-1" because were only concerned of number of keys which is 32 not 33
    //count($characters) = 33
   
$x = mt_rand(0, count($characters)-1);
    if(!
in_array($x, $keys)) {
      
$keys[] = $x;
    }
}

foreach(
$keys as $key){
  
$random_chars .= $characters[$key];
}
echo
$random_chars;
?>
Anonymous
6.03.2010 3:41
Generate a random 5 character A-Z0-9  string

<?php
for ($i=0; $i<6; $i++) {
   
$d=rand(1,30)%2;
    echo
$d ? chr(rand(65,90)) : chr(rand(48,57));
}
?>

# php -r 'for ($i=0; $i<6; $i++) { $d=rand(1,30)%2; echo $d ? chr(rand(65,90)) : chr(rand(48,57)); } echo "\n";'
14BW1A
mike at marylandwebsites dot net
24.02.2010 3:42
Rather then counting the rows or running the RAND in my query, I find this to work just fine.
This code is used to display business highlights at random

Would love to get feedback on this

<?php
// First get the last id from the table

$SQL = "SELECT * FROM HIGHLIGHTS ORDER BY highlight_id DESC LIMIT 1";
$result = mysql_query( $SQL );
while(
$row = mysql_fetch_array( $result ) ) {
$ending_id = $row["highlight_id"];
}

// I only want the 5 most recent entries
// So I just subtract 5 from the last ID

$starting_id = $ending_id - 5;

// Because I we don't want a nagitive number I just
// make sure that the starting ID is at least 1

if($starting_id <= 0){
   
$starting_id = "1";
    }
 
// now I run the the $starting_id $ending_id at RAND

$howey = rand($starting_id, $ending_id);

// Now I use howey as my id

$SQL = "SELECT * FROM HIGHLIGHTS WHERE highlight_id = '$howey'";
$result = mysql_query( $SQL );
while(
$row = mysql_fetch_array( $result ) ) {
$highlight_id = $row["highlight_id"];
$highlight_title = $row["highlight_title"];
}
echo
"$highlight_id $highlight_title";
?>
djindjojlo AT gmail DOT com
20.02.2010 14:52
a very easy random letters and numbers... one of my beginers scripts :)

<?php

$abc
= array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");
$num= array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
echo
$abc[rand(0,25)];
echo
$num[rand(0,9)]; 
?>
John Galt
2.01.2010 20:24
Another way to create an array of random numbers where there are no identical numbers.

($n = number of random numbers to return in the array
$min = minimum number
$max = maximum number)

<?php
 
function uniqueRand($n, $min = 0, $max = null)
 {
  if(
$max === null)
  
$max = getrandmax();
 
$array = range($min, $max);
 
$return = array();
 
$keys = array_rand($array, $n);
  foreach(
$keys as $key)
  
$return[] = $array[$key];
  return
$return;
 }
?>
Hugo Scott hrmscott at hotmail dot com
29.07.2009 16:52
Here's a simple function to generate a random date between a start date and an end date.

It is inclusive of BOTH dates - so using dates 2009-04-01 and 2009-04-03 would generate a random date that could be 2009-04-01, 2009-04-02 or 2009-04-03.

It won't work if the end date is prior to the start date and if you use a non-existant date (eg 2009-02-30) it defaults to 1970-01-01

the longer version:
<?php
function makeRandomDateInclusive($startDate,$endDate){
   
$days = round((strtotime($endDate) - strtotime($startDate)) / (60 * 60 * 24));
   
$n = rand(0,$days);
    return
date("Y-m-d",strtotime("$startDate + $n days"));   
}
?>

and the one-line version for compactness freaks:
<?php
function makeRandomDateInclusive($startDate,$endDate){   
    return
date("Y-m-d",strtotime("$startDate + ".rand(0,round((strtotime($endDate) - strtotime($startDate)) / (60 * 60 * 24)))." days"));
}
?>

it is called like this
<?php
echo makeRandomDateInclusive('2009-04-01','2009-04-03');
?>
Hope this is of some use to someone
Greg R.
16.06.2009 1:49
I thought this function (random color) might be of use to someone [to create and return a random hex for HTML colors]:

<?php
function get_random_color()
{
    for (
$i = 0; $i<6; $i++)
    {
       
$c .=  dechex(rand(0,15));
    }
    return
"#$c";
}
?>
alex at bimpson dot com
15.06.2009 18:30
A very easy method for generating for generating an array of UNIQUE random numbers:

<?php

$rand
= array();
while (
count($rand) < $total ) {
   
$r = mt_rand($min,$max);
    if ( !
in_array($r,$rand) ) {
       
$rand[] = $r;
    }
}

?>

whereby $total is the number of unique random numbers you want, $min is the lowest possible value and $max is the highest possible value.
david [at] ddrewdesign [dot] com
27.05.2009 3:21
To Jano and Peta:

Thanks for the code. In real world usage, I only had one problem with it: It will never return the first result of the array (or it will return nothing if there's only one item in the array). To remedy this, I simply subtracted 1 from

<?php
$rand
= rand(1,$max);
?>

like so:

<?php
$rand
= rand(1,$max)-1;
?>

Thanks though, for the code you supplied. It was exactly what I needed.
kyle dot florence [@t] gmail dot com
9.05.2009 0:23
Improved random string generation function:

<?php
// Generate a random character string
function rand_str($length = 32, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890')
{
   
// Length of character list
   
$chars_length = (strlen($chars) - 1);

   
// Start our string
   
$string = $chars{rand(0, $chars_length)};
   
   
// Generate random string
   
for ($i = 1; $i < $length; $i = strlen($string))
    {
       
// Grab a random character from our list
       
$r = $chars{rand(0, $chars_length)};
       
       
// Make sure the same two characters don't appear next to each other
       
if ($r != $string{$i - 1}) $string .=  $r;
    }
   
   
// Return the string
   
return $string;
}
?>
admin at djs-music dot com
25.04.2009 19:13
A nice function to generate a random string, using any character:

<?php
function generateRandStr($length){
     
$randstr = "";
      for(
$i=0; $i<$length; $i++){
        
$randnum = mt_rand(0,61);
         if(
$randnum < 10){
           
$randstr .= chr($randnum+48);
         }else if(
$randnum < 36){
           
$randstr .= chr($randnum+55);
         }else{
           
$randstr .= chr($randnum+61);
         }
      }
      return
$randstr;
   }
?>

Simply use:
generateRandStr(10);

Sample output: $%29zon(4f
petabyte.se
15.03.2009 17:56
As an further optimization on janoserki[at]gmail[dot]com previous post i would recommend that you optimize you first part of php/sql code to something like this.

<?php
// estimate the number of rows in a table
$lekerdezes = mysql_query("select count(*) as rows from table");
while (
$row = mysql_fetch_assoc($lekerdezes))
{
   
$max = $row["rows"];
}
?>
the count(*) is much faster for the database than grabbing the hole dataset from the table.
janoserki [at] gmail [dot] com
4.03.2009 9:16
Easy way for mysql: random row
the original form is: "... order by rand()"
but this is not the best way, because it's very slow by a big database (it can take more minutes to complete the request!)
My suggestion:

<?php
// estimate the number of rows in a table
$lekerdezes = mysql_query("select * from table");
$max = mysql_num_rows($lekerdezes);

// pick one
$rand = rand(1,$max);

$lekerdezes2 = mysql_query("select * from table limit $rand, 1");

// that's all folks :)

?>
whatchildisthis at gmail dot com
7.12.2008 1:00
I also enjoy making one-liners.

Here's a non-regular expression approach. It generates a random 32 character string consisting of, by default, only A-Z, a-z, and 0-9, but you can change the value of $a for other characters. The random string will be in variable $s after this line.

<?php
for ($s = '', $i = 0, $z = strlen($a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')-1; $i != 32; $x = rand(0,$z), $s .= $a{$x}, $i++);
?>

If you don't want the same character to appear beside itself, use this:

<?php
for ($i = 0, $z = strlen($a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890')-1, $s = $a{rand(0,$z)}, $i = 1; $i != 32; $x = rand(0,$z), $s .= $a{$x}, $s = ($s{$i} == $s{$i-1} ? substr($s,0,-1) : $s), $i=strlen($s));
?>

For those of you who want both as a function, use this:

<?php
function rand_chars($c, $l, $u = FALSE) {
 if (!
$u) for ($s = '', $i = 0, $z = strlen($c)-1; $i < $l; $x = rand(0,$z), $s .= $c{$x}, $i++);
 else for (
$i = 0, $z = strlen($c)-1, $s = $c{rand(0,$z)}, $i = 1; $i != $l; $x = rand(0,$z), $s .= $c{$x}, $s = ($s{$i} == $s{$i-1} ? substr($s,0,-1) : $s), $i=strlen($s));
 return
$s;
}
?>

string $c is the string of characters to use.
integer $l is how long you want the string to be.
boolean $u is whether or not a character can appear beside itself.

Examples:
rand_chars("ABCEDFG", 10) == GABGFFGCDA
rand_chars("ABCEDFG", 10, TRUE) == CBGFAEDFEC
adam at greatbigmassive dot com
2.12.2008 14:10
I've noticed alot of people doing long winded random string generators so I thought I'd post my one liner to give a bit of a fresh approach.

The concept is simple. The rand() function generates a number made up of 10 different digits. (0,1,2,3,4,5,6,7,8,9).
To generate an equivalent string I only need 10 alpha characters to replace the numbers.

I am using (p,q,r,s,t,u,v,w,x,y). I chose these letters because they don't include any characters that resemble numbers and was the best set generated by the chr() function.

Anyway, to create a 6 character random string I do this:

$rand = preg_replace("/([0-9])/e","chr((\\1+112))",rand(100000,999999));

The length of the string is based on the length of the random number generated.
This would also mean you could generate a random string at a random length too if you wanted.

Adam
amossoma at o2 dot pl
19.11.2008 10:40
<?php
function generateRandomString($length = 10, $letters = '1234567890qwertyuiopasdfghjklzxcvbnm')
  {
     
$s = '';
     
$lettersLength = strlen($letters)-1;
     
      for(
$i = 0 ; $i < $length ; $i++)
      {
     
$s .= $letters[rand(0,$lettersLength)];
      }
     
      return
$s;
  }
?>
opbarnes
20.10.2008 21:33
Generate a random 5 character alpha string:

<?php
print preg_replace('/([ ])/e', 'chr(rand(97,122))', '     ');
?>
szczepan[DoT]Krol #HT# gmail [knowRest]
14.08.2008 15:55
Heres another function to generate Random Unique numbers.

<?php
class UniqueRand{
  var
$alreadyExists = array();

  function
uRand($min = NULL, $max = NULL){
   
$break='false';
    while(
$break=='false'){
     
$rand=mt_rand($min,$max);

      if(
array_search($rand,$this->alreadyExists)===false){
       
$this->alreadyExists[]=$rand;
       
$break='stop';
      }else{
        echo
" $rand already!  ";
       
print_r($this->alreadyExists);
      }
    }
    return
$rand;
  }
}
$rand=new UniqueRand();


echo
"<b> ". $rand->uRand(0,5)."</b>";
echo
"<b> ". $rand->uRand(5,5)."</b>";
echo
"<b> ". $rand->uRand(10,5)."</b>";

?>
thomas at tgohome dot com
31.07.2008 17:46
You don't need fancy queries to grab a random row(s) from MySQL; it's actually quite simple. In fact, you can do it in a single query.

<?php
$random_rows
= array();

$query = mysql_query("SELECT * FROM tablename ORDER BY RAND() LIMIT 1");

while(
$row = mysql_fetch_array($query))
{
    
$random_rows[] = $row;
}
?>

You can extend LIMIT to any number, so you can select 10 random rows. Also, because it uses ORDER BY the rows are always unique if you select 10 rows, for example.

This might work on other database systems such as MsSQL and PostgreSQL but I haven't tested them.
Anonymous
31.07.2008 1:29
quick way to generate randomish numbers and simple strings.
no messing around with functions, so you can just pop the line into the middle of your existing code.

not the most perfect for sure, but ok for plenty of situations...

<?php

$random_number
= intval( "0" . rand(1,9) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9) ); // random(ish) 5 digit int

$random_string = chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)); // random(ish) 5 character string

?>

hope someone finds it useful for somthing.

regards,
deeeeeen alxndr0u
gacek at my dot planet
29.05.2008 13:36
For some people who would need to generate random string:

<?php

function random_letters ($numofletters) {
    if (!isset(
$numofletters)) $numofletters = 10; // if $numofletters is not specified sets to 10 letters
   
$literki = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'W');
   
$ilosc_literek = count($literki);
    for (
$licz = 0; $licz < $numofletters; $licz++) {
   
$rand = rand(0, $ilosc_literek-1);
   
$vercode = $vercode.$literki[$rand];
    }
}

?>
davidsteinsland [at] gmail [dot] com
26.04.2008 21:27
emad_ramahi at hotmail dot com:
I've actually noticed that with a large dataset (100k rows), the query dramatically slows down the server and performance is way too bad.

The way I see it, you have to workable solutions:

Using PHP:

<?php
//$Table holds the name of the table we're getting the random row from
//$Rows specifies how many rows we need to fetch
function mysql_rand ($Query, $Rows = 1) {
   
//getting the table name from $query
    //what you can do, is replace the $query argument with $table,
    //this way to dont have to search for the table's name
   
$SQL = sprintf ('SELECT COUNT(*) FROM %s', substr ($query, stripos ($query, 'from')+5, strpos ($query, ' ')));
   
   
$Max = mysql_result (mysql_query ($SQL), 0);
   
$Random = rand (0, $Max);
   
   
//If the random number is 99, and the database only has 100 rows
    //We'll subtract the random number, so we don't exceed 100, thus preventing a MySQL error message
   
return $Query . sprintf ('LIMIT %d, %d', ($Max < $Rows) ? 0 : (($Random > $Max - $Rows) ? $Max - $Rows : $Random), $Rows);
}

//Instead of using MySQL's RAND(), we use LIMIT to fetch rows
//E.g. LIMIT 5,9 fetches from row 5, and the subsequent 9
$SQL = mysql_rand ('SELECT row FROM table'); //SELECT row FROM table LIMIT x, y
?>

or SQL:
SELECT * FROM Table T JOIN (SELECT FLOOR(MAX(ID)*RAND()) AS ID FROM Table) AS x ON T.ID >= x.ID LIMIT 1;
emad_ramahi at hotmail dot com
9.03.2008 10:16
Hi All,
For those whom wants to get a random value from MySQL:
select coumnName from TableName order by rand()
Anonymous
25.02.2008 21:37
Using the script below with rand() instead of mt_rand(),
I was suprised to find many "words" and part of "phrases" in common.

mt_rand() is highly recomanded when you want to build test cases.

<?php
 $ressbdd
= mysql_connect("localhost", "usr", "pass")
  or  die(
"Could not connect: " . mysql_error());
 for(
$i=0;$i<100000;$i++){
 
$xx1=mt_rand(15,80);
 
$texte = phrase($xx1);
 
$sql = 'INSERT into phrases.valeurs set valeur = \'' . $texte . '\'';
 
mysql_query( $sql , $ressbdd );
 }
//=============================================
function phrase($n){
 
$phrase='';
 for(
$i=0;$i<$n;$i++){
 
$xx2=mt_rand(2,20);
 
$phrase.=mot($xx2) . ' ';
 }
 return(
substr($phrase,0,-1).'.'); // phrase ends with a .
}
//=============================================
function mot($n){
 if(
$n<=0)  return 'hello';
 if(
$n>=31) return 'world';
 
$voyelle =Array('a','e','i','o','u','y');
 
$consonne=Array(
'b','c','d','f','g','h','j','k','l','m',
'n','p','q','r','s','t','v','w','x','z');
 
$mot='';
 for(
$i=0;$i<$n;$i++){
  if(
$i%2==0){
  
$xx3=mt_rand(0,19);
  
$mot.=$consonne[$xx3];
  }else{
  
$xx4=mt_rand(0,5);
  
$mot.=$voyelle[$xx4];
  }
 }
 return
$mot;
}
?>
Anonymous
6.11.2007 10:24
Note, the function used by PHP to constrain a random number between (min, max) is the following:

$number = $min + (($max - $min + 1) * ($number / ($rand_max + 1));

where the following:
$number - the initially generated random number
$min - the minimum in the range
$max - the maximum in the range
$rand_max - the maximum possible random value

What this algorithm does is constrain the generated number to a 0-1 range, then multiply it against your range, mapping the two to each other.

In practice you'll see the following results:
For a generated $number of 16384 and a $rand_max of 32768:
rand(0, 10) = 5
rand(0, 100) = 50
rand(0, 1000) = 500

with the additional property that if the range you're asking for is larger than $rand_max, random numbers will be in a multiple of $max/$rand_max.
Ishtar
10.09.2007 15:18
A small comment on phpdev-dunnbypauls conclusion that rand() only generates numbers that are a multiply of 3.
<?php
$n
= rand(0,100000); // with MAX_RAND=32768
?>
Since, 100000/32768=3.05 you get multiples of 3. The random integer will be multiplied by 3.05 to fit between 0 and 100000. rand() works fine, if you don't ask for bigger numbers then RAND_MAX.
rok dot kralj at gmail dot com
16.06.2007 9:43
rand function returns just a whole numbers. If you want a random float, then here's an elegant way:

<?php
function random_float ($min,$max) {
   return (
$min+lcg_value()*(abs($max-$min)));
}
?>
bozo_z_clown at yahoo dot com
24.05.2007 2:36
Note that the automatic seeding seems to be done with the current number of seconds which means you can get the same results for several runs on a fast server.  Either call srand() yourself with a more frequently changing seed or use mt_rand() which doesn't appear to suffer from the problem.
jont at live dot co dot uk
5.04.2007 12:42
isn't this just a simpler way of making a random id for somthing? I mean i know that there is a very slight chance that a duplicate could be made but its a very, very, very small chance, nearly impossible.

$rand = mt_rand(0, 32);
$code = md5($rand . time());
echo "$code";

and if you don't want it the md5 can be removed, I've just added it as a prefer it there :)

Jon
phpdev at dunnbypaul dot net
8.03.2007 5:51
Here's an interesting note about the inferiority of the rand() function. Try, for example, the following code...

<?php
$r
= array(0,0,0,0,0,0,0,0,0,0,0);
for (
$i=0;$i<1000000;$i++) {
 
$n = rand(0,100000);
  if (
$n<=10) {
   
$r[$n]++;
  }
}
print_r($r);
?>

which produces something similar to the following output (on my windows box, where RAND_MAX is 32768):

Array
(
    [0] => 31
    [1] => 0
    [2] => 0
    [3] => 31
    [4] => 0
    [5] => 0
    [6] => 30
    [7] => 0
    [8] => 0
    [9] => 31
    [10] => 0
)

Within this range only multiples of 3 are being selected. Also note that values that are filled are always 30 or 31 (no other values! really!)

Now replace rand() with mt_rand() and see the difference...

Array
(
    [0] => 8
    [1] => 8
    [2] => 14
    [3] => 16
    [4] => 9
    [5] => 11
    [6] => 8
    [7] => 9
    [8] => 7
    [9] => 7
    [10] => 9
)

Much more randomly distributed!

Conclusion: mt_rand() is not just faster, it is a far superior algorithm.
Patrick Daryll G.
2.03.2007 15:51
Using rand()%x is faster than rand(0,x) yes, but it is wrong.
Consider the following example:
RAND_MAX is 32768 (like on Windows for example)
You use rand()%30000
Imagine rand() returns a value between 30000 and 32768.
Modulo could make any value between 0 and 2768, but not any between 2769 and 29999 (except the value is below 29999).
This would double the chance of getting a number between 0 and 2768, which is speaking against the principles of randomness.
ludicruz at yahoo dot com
27.09.2006 14:42
frank, nick at nerdynick dot com, and kniht
this is now O(n) instead of O(n^2) ish...

<?php
function rand_permute($size, $min, $max)
{
   
$retval = array();
   
//initialize an array of integers from $min to $max
   
for($i = $min;$i <= $max;$i++)
    {
       
$retval[$i] = $i;
    }
   
//start with the the first index ($min).
    //randomly swap this number with any other number in the array.
    //this way we guarantee all numbers are permuted in the array,
    //and we assure no number is used more than once (technically reiterating prev line).
    //therefore we don't have to do the random checking each time we put something into the array.
   
for($i=$min; $i < $size; $i++)
    {
       
$tmp = $retval[$i];
       
$retval[$i] = $retval[$tmpkey = rand($min, $max)];
       
$retval[$tmpkey] = $tmp;
    }
    return
array_slice($retval, 0, $size);
}
?>
umpalump at poczta dot neostrada dot pl
13.06.2005 14:32
Random numbers with Gauss distribution (normal distribution).
A correct alghoritm. Without aproximations, like Smaaps'
It is specially usefull for simulations in physics.
Check yourself, and have a fun.

<?php

function gauss()
{  
// N(0,1)
    // returns random number with normal distribution:
    //   mean=0
    //   std dev=1
   
    // auxilary vars
   
$x=random_0_1();
   
$y=random_0_1();
   
   
// two independent variables with normal distribution N(0,1)
   
$u=sqrt(-2*log($x))*cos(2*pi()*$y);
   
$v=sqrt(-2*log($x))*sin(2*pi()*$y);
   
   
// i will return only one, couse only one needed
   
return $u;
}

function
gauss_ms($m=0.0,$s=1.0)
{  
// N(m,s)
    // returns random number with normal distribution:
    //   mean=m
    //   std dev=s
   
   
return gauss()*$s+$m;
}

function
random_0_1()
{  
// auxiliary function
    // returns random number with flat distribution from 0 to 1
   
return (float)rand()/(float)getrandmax();
}

?>

JanS
student of astronomy
on Warsaw University
smaaps at kaldamar dot de
7.06.2005 7:44
Lately I needed some random numbers with a gaussian (normal) distribution, not evenly distributed as the numbers generated by rand(). After googling a while, I found out that there is no perfect algrorithm that creates such numbers out of evenly distruted random numbers but a few methods that have similar effect. The following function implements all three algorithms I found- The the last two methods create numbers where you can find a lower and upper boundary and the first one will create a number from time to time (such as one in every 10000) that may be very far from the average value. Have fun testing and using it.

<?php
function gauss($algorithm = "polar") {
   
$randmax = 9999;
   
    switch(
$algorithm) {
       
       
//polar-methode by marsaglia
       
case "polar":
           
$v = 2;
            while (
$v > 1) {
               
$u1 = rand(0, $randmax) / $randmax;
               
$u2 = rand(0, $randmax) / $randmax;

               
$v = (2 * $u1 - 1) * (2 * $u1 - 1) + (2 * $u2 - 1) * (2 * $u2 - 1);
            }
           
            return (
2* $u1 - 1) * (( -2 * log($v) / $v) ^ 0.5);
       
       
// box-muller-method
       
case "boxmuller":
            do {
               
$u1 = rand(0, $randmax) / $randmax;
               
$u2 = rand(0, $randmax) / $randmax;                   
               
               
$x = sqrt(-2 * log($u1)) * cos(2 * pi() * $u2);
            } while (
strval($x) == "1.#INF" or strval($x) == "-1.#INF");
           
           
// the check has to be done cause sometimes (1:10000)
            // values such as "1.#INF" occur and i dont know why
           
           
return $x;

       
// twelve random numbers  
       
case "zwoelfer":
           
$sum = 0;
            for (
$i = 0; $i < 12; $i++) {
               
$sum += rand(0, $randmax) / $randmax;
            }
            return
$sum;
     }      
}
?>
relsqui at armory dot com
21.01.2005 11:23
Don't forget, it's faster to use bitwise operations when you need a random number that's less than some power of two. For example,

<?php
rand
()&1;
// instead of
rand(0,1);
// for generating 0 or 1,

rand()&3;
// instead of
rand(0,3);
// for generating 0, 1, 2, or 3,

rand()&7;
// instead of
rand(0,7)
// for generating 0, 1, 2, 3, 4, 5, 6, or 7,
?>

and so on. All you're doing there is generating a default random number (so PHP doesn't have to parse any arguments) and chopping off the piece that's useful to you (using a bitwise operation which is faster than even basic math).



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)