PHP/Math/mt rand

Материал из Web эксперт
Перейти к: навигация, поиск

Finding a random line of a file

 
<?php
function randomint($max = 1) {
  $m = 1000000;
  return ((mt_rand(1,$m * $max)-1)/$m);
}
?>
$line_number = 0;
$fh = fopen("data.txt","r") or die($php_errormsg);
while (! feof($fh)) {
    if ($s = fgets($fh)) {
        $line_number++;
        if (randomint($line_number) < 1) {
            $line = $s;
        }
    }
}
fclose($fh) or die($php_errormsg);
?>



Generate Password()

 
<?php
function GeneratePassword($min = 5, $max = 8) {
  $ValidChars = "abcdefghijklmnopqrstuvwxyz123456789";
  $max_char = strlen($ValidChars) - 1;
  $length = mt_rand($min, $max);
  $password = "";
  for ($i = 0; $i < $length; $i++) {
    $password .= $ValidChars[mt_rand(0, $max_char)];
  }
  return $password;
}
echo "New Password = " . GeneratePassword() . "\n";
echo "New Password = " . GeneratePassword(4, 10) . "\n";
?>



Generate random floating-point values from 0 to 10 with two decimals

 
<?php 
function frand($min, $max, $decimals = 0) { 
    $scale = pow(10, $decimals); 
    return mt_rand($min * $scale, $max * $scale) / $scale; 
} 
echo "frand(0, 10, 2) = " . frand(0, 10, 2) . "\n"; 
?>



Generate random numbers

 
<?php
function frand($min, $max, $precision = 1) {
  $scale = 1/$precision;
  return mt_rand($min * $scale, $max * $scale) / $scale;
}
echo "frand(0, 10, 0.25) = " . frand(0, 10, 0.25) . "\n";
?>



Get a random value from 5 to 25.

 
<?php 
echo "rand(5, 25) = " . rand(5, 25) . "\n"; 
echo "mt_rand(5, 25) = " . mt_rand(5, 25) . "\n"; 
?>



Get random values from �10 to 10.

 
<?php 
echo "rand(-10, 10) = " . rand(-10, 10) . "\n"; 
echo "mt_rand(-10, 10) = " . mt_rand(-10, 10) . "\n"; 
?>



int mt_rand ( [int min, int max] ) returns random numbers, similar to the rand( ).

 
It uses the Mersenne Twister algorithm to generate "better" random numbers (i.e., more random), and is often preferred.
<?
    $mtrand = mt_rand( );
    $mtrandrange = mt_rand(1,100);
?>



Random floating-point values from 0 to 10 with two decimals

 
<?php
function frand($min, $max, $decimals = 0) {
  $scale = pow(10, $decimals);
  return mt_rand($min * $scale, $max * $scale) / $scale;
}
echo "frand(0, 10, 2) = " . frand(0, 10, 2) . "\n";
?>



Random numbe with precision

 
<?php 
function frand($min, $max, $precision = 1) { 
    $scale = 1/$precision; 
    return mt_rand($min * $scale, $max * $scale) / $scale; 
} 
echo "frand(0, 10, 0.25) = " . frand(0, 10, 0.25) . "\n"; 
?>



Random values are not restricted to positive integers. The following example shows how to get random values from -10 to 10.

 
<?php
echo "rand(-10, 10) = " . rand(-10, 10) . "\n";
echo "mt_rand(-10, 10) = " . mt_rand(-10, 10) . "\n";
?>