Pseudo-Random vs. True Random

A Simple Visual Example

Once upon a time I stumbled across Random.org, an awesome true random number generation service. The difference between true random number generators (TRNGs) and pseudo-random number generators (PRNGs) is that TRNGs use an unpredictable physical means to generate numbers (like atmospheric noise), and PRNGs use mathematical algorithms (completely computer-generated). You can read more about this at Random.org and Wikipedia.

I was messing around with the Bitmap Generator, when I decided to create a pseudo-random generated bitmap of my own to compare. And wouldn't you know it, the very first thing I tried showed a pattern!



Random.org Bitmap

Random bitmap based on atmospheric noise

PHP rand() on Windows Bitmap

Random bitmap based on PHP's rand() function in Windows

Yikes! Not so "random" eh?

Not many PRNGs will produce an obvious visual pattern like this, it just so happens to be a really bad combination of language (PHP), operating system (Windows), and function (rand()). I ran the same code in a Linux environment, and it did not have an obvious visual pattern. I also ran the same code again in Windows, but using PHP's mt_rand() function instead, which utilizes the Mersenne Twister to generate a better random number, and it did not have an obvious visual pattern. If you want to know more about why this happens, read this.

Here's the code I used to generate the bitmap:

<?php // Requires the GD Library header("Content-type: image/png"); $im = imagecreatetruecolor(512, 512) or die("Cannot Initialize new GD image stream"); $white = imagecolorallocate($im, 255, 255, 255); for ($y = 0; $y < 512; $y++) { for ($x = 0; $x < 512; $x++) { if (rand(0, 1)) { imagesetpixel($im, $x, $y, $white); } } } imagepng($im); imagedestroy($im);

Basically, it's the sort of thing you wouldn't need worry about with a true random number generator, unless somehow it's security was breached (a whole other topic really). Pseudo-random number generators vary greatly in quality. Some are horrible, some are extraordinary, but none are true.