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.
Are you using rand()
? Consider "generating a better random value".
Addendum; it's always good to see two sides of a coin.
mt_rand() is an improvement over rand(). But, random numbers are generated from a sequence, so...
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.
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