Looping through rm_rand, storing highest and lowest values

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

Looping through rm_rand, storing highest and lowest values

Post by impulse() »

I have just wrote a little script that generates 1,000,000 random numbers using rm_rand and stores the highest and lowest values generated. It seems to work in the fact the highest is always higher than the lowest but I unexplainable feeling that it's not working correctly.
Could somebody tell me if this is working as it should be:

Code: Select all

$i = 0;
while ($i < 1000000) {

  if (isset($rand)) {
    $rand2 = $rand;
  }

  $rand = mt_rand();

  if (isset($rand2)) {
    if ($rand < $rand2) {
      $lowest = $rand;
    }
    if ($rand > $rand2) {
      $highest = $rand;
    }
  }
  $i++;
}
echo "The lowest random number generated was: ", $lowest, "\n";
echo "The highest random number generated was: ", $highest, "\n";
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

Code: Select all

$lowest = 9999999999;
$max = 0;

for($x = 0; $x < 1000000; $x++)
{
  $rand = mt_rand();

  if($rand > $max) $max = $rand;
  if($rand < $min) $min = $rand;
}

echo 'Highest: ' . $max;
echo 'Lowest: ' . $min;
That would be easier. Someone will know a quicker way though ;)
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

use mt_getrandmax() to initialize $lowest. Other than that I can't see how you could improve that.
Post Reply