5

Are PHP random numbers predictable? if so, how difficult would it be to predict random numbers that are in a range of 1 to 32? and is there any way to make it unpredictable?

<?php
function rand_best($min, $max) {
    $generated = array();
    for ($i = 0; $i < 100; $i++) {
        $generated[] = mt_rand($min, $max);
    }
    shuffle($generated);
    $position = mt_rand(0, 99);
    return $generated[$position];
}
?>
2
  • 3
    Since you are using mt_rand(), you should read up on the Mersenne Twister algorithm if you want to know how it works. Commented Jan 5, 2012 at 11:49
  • 1
    Additionally, mt_rand() provides better quality than rand() (which is notably flawed). BTW, not random, not uniform and predictable are pretty different concepts: you just can't predict the next number if you don't know the seed. Commented Jan 5, 2012 at 11:53

3 Answers 3

7

The discussion around how random random-functions in programming is, is ancient.

Take a look at this: http://en.wikipedia.org/wiki/Random_number_generation

Anyway. The random-functions are so good today that they are (what I would call) as near random as possible. There's no way to predict a result between 1,32 (or any other number for that sake). The deal is that the numbers are not truly random because a computer can not do such a operation.

I'd say the rand-functions is more than good enough unless you are writing something for Pentagon

Sign up to request clarification or add additional context in comments.

4 Comments

Some computers have hardware devices producing really random numbers.
That's true. I've read on this page random.org/randomness (should be read!) that they use a radioactive source, because they are truly random.
I think the some very latest Intel processors have a random generating privileged instruction.
"Writing for the Pentagon" or even more intense: making an HTTPS request. Seriously, good randomness sources are needed everywhere or things as we know them wouldn't function at all. I don't think it's right to shove the concept under the rug because it might not be immediately intuitive. You don't need radioactive sources for those basic cases either, and all modern kernels are able to gather good-enough randomness from common sources to feed a pool used for seeding PRNGs. On-topic answer.
2

Assuming a Linux system, you could seed your pseudo random number generator with /dev/urandom (or read from that), or possibly /dev/random (be careful, it can block).

Comments

1

After PHP 7 version you can use random_int() too.
Take a look at this: http://php.net/random_int

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.