Error free since 03:14:07 UTC January 19, 2038.

How good is Rand() in PHP?

Not Good:

I needed an image of random noise (to demonstrate that it had a [http://en.wikipedia.org/wiki/Box-counting_dimension](box-counting dimension) of 3). So I wrote the following script to throw one together, but it doesn't look random enough.

Randomized image in PHP with rand

    $img = imageCreateTrueColor(512, 512);
    for ($i=0; $i < 512; $i++) {
     for ($j=0; $j < 512; $j++) {
            $c=mt_rand(0,255);
            $col = imageColorAllocate($img, $c, $c, $c);
            imagesetpixel($img, $i, $j, $col);
        }
    }
    header("Content-Type: image/png");
    imagepng($img);
    imagedestroy($img);

Up close:

If we zoom in by a factor of five it looks even worse.

It'll be ok

Randomized image in PHP with mt_rand

A simple change to "mt_rand()" from "rand()" and the picture looks much much better. The filesize also jumps from 33k to 167k, which means that the PNG algorithm isn't able to compress the picture near as well.

Details

This is PHP 4.4.2 on Windows.



Programming Math etc

What I've said lately

Loading feeds

More of me on the web