PHP rand function (or not so rand)
Posted
by
Badr Hari
on Programmers
See other posts from Programmers
or by Badr Hari
Published on 2011-11-24T19:16:28Z
Indexed on
2011/11/25
2:17 UTC
Read the original article
Hit count: 350
php
|random-numbers
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:
513:
Edit: I'm running xampp on Windows to test it.
© Programmers or respective owner