PHP Random Function – Understanding PHP rand()

PHPrandom

I was testing PHP rand function to write on a image. Of course the output shows that it's not so random. The code I used:

<?php 
header('Content-Type: image/png');
$lenght = 512;
$im = imagecreatetruecolor($lenght, $lenght);
$blue = imagecolorallocate($im, 0, 255, 255);
for ($y = 0; $y < $lenght; $y++) {
    for ($x = 0; $x < $lenght; $x++) {
        if (rand(0,1) == 0) {
            imagesetpixel($im, $x, $y, $blue);
        }
    }
}       
imagepng($im);
imagedestroy($im);
?>

My question is, if I use image width/lenght (variable $lenght in this example) number like 512, 256 or 1024, it is very clear that it's not so random. When I change the variable to 513 for an example, it is so much harder for human eye to detect it. Why is that? What is so special about these numbers?

512:

512 pixels

513:

513 pixels

Edit: I'm running xampp on Windows to test it.

Best Answer

This is a known bug which isn't related to PHP, but inherant to the windows API used by PHP. The random function of this API is very bad.

This problem will not exist on Linux or MacOS (or any other system).

You can learn more about this here: http://cod.ifies.com/2008/05/php-rand01-on-windows-openssl-rand-on.html

If it is more visible with some value, this is mostly because of the dimensions of the image, and the clear lines formed by the pattern. This is definitively linked to our perception, some patterns looks more random than others.

The human brain random function is very buggy. What we see as random or not isn't reliable at all. This is a known phenomenon but off topic here.

Related Topic