jest
jest

Reputation: 699

random number generator in php

i wrote a php script to generate random values between 1 and 99999999999999999999 (that's 20 9's).

The script is like this:

$maxq=20;
for($i=1;$i<=$maxq;$i++) {
    $min=pow(10,$i);
    $max=(pow(10,$i)*10)-1;
    echo $min."<br>";
    echo $max."<br>";
    echo mt_rand($min,$max)."<br>----<br>";
}

but after 10 digit, php generates scientific notations like 1.0E+19 and the random numbers generated are a mess.

I guess think is because of my hardware imitations (OS: Win XP 32 bit).

What can i do to over come this? any help?

Thanks.

Upvotes: 3

Views: 11602

Answers (4)

Greg
Greg

Reputation: 1

I build upon "bramp" response. I wanted 25 lines, of 25 randomly generated digits:

<?php
  $num = '';
  while($i < 25)
  {
    for ($n = 0; $n < 25; $n++)
      $num .= mt_rand(0, 9);
      echo $num . "</br>";
  $num = '';
  $i++;
  }
?>

Upvotes: 0

bramp
bramp

Reputation: 9741

You can use the BC Math Functions to overcome the limit. Or if you aren't going to be doing calculations with your random number, you can create a random 20 digit string. Something like:

$num = '';
for ($i = 0; $i < 20; $i++)
   $num .= mt_rand(0, 9);
echo $num;

Upvotes: 8

  1. In windows platform it can be use getrandmax() ,it gives only 32768.
  2. so you need range larger than 32768.
  3. specifying min and max
  4. It will allow you to create a range larger than 32768
  5. so it will consider using mt_rand() instead of getrandmax()

For Example,

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

echo rand(5, 15);
?>

Upvotes: 1

strager
strager

Reputation: 90062

You could generate n random digits and concatenate them into one large string.

function randomDigits($numDigits) {
    if ($numDigits <= 0) {
        return '';
    }

    return mt_rand(0, 9) . randomDigits($numDigits - 1);
}

// Or an iterative approach
function randomDigitsLame($numDigits) {
    $digits = '';

    for ($i = 0; $i < $numDigits; ++$i) {
        $digits .= mt_rand(0, 9);
    }

    return $digits;
}

$maxq = 20;

for ($i = 1; $i <= $maxq; $i++) {
    echo $i . "<br>\n";
    echo randomDigits($i) . "<br>\n----<br>\n";
}

Upvotes: 10

Related Questions