2

I need to generate about 5,000 random numbers in my script, but the CPU is so fast that I see tendencies in my random numbers.

For example, in the 100 first iterations, I get 80 values between 70 and 99 with rand(0,100);, which can be a REAL inconvenient.

Is there a way to solve such issue, or is randomness not achievable anymore in 2012?

I believe there could be a possibility of generating random numbers from a function executing a random number of times... but I can't figure out one.

Adam Strudwick
  • 12,671
  • 13
  • 31
  • 41

4 Answers4

5

Are you using rand()? Consider "generating a better random value".

Addendum; it's always good to see two sides of a coin.

Community
  • 1
  • 1
Dan Lugg
  • 20,192
  • 19
  • 110
  • 174
1

rand is seeded by time. mt_rand may work better for you. If you want even better randomness, you can use openssl_random_pseudo_bytes (if available) or /dev/[u]random if you don't have access to that and are on a system where it is available. If you use those, you have to convert the bytes with hexdec(bin2hex()) to get decimal digits, and probably truncate them after that.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
0

mt_rand() is an improvement over rand(). But, random numbers are generated from a sequence, so...

goat
  • 31,486
  • 7
  • 73
  • 96
0

Use this function :

function Random($length = 210) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
    $randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}

You can change 210 to any number you want hope this helps

Dustin.php
  • 11
  • 6
  • If you're just going to copy/paste and then change function names, at least cite where you copied it from: http://stackoverflow.com/a/4356295/1400370 – Jamie Taylor Oct 29 '13 at 10:53