Does rand() Function in PHP Return Fair Result?

Posted
Comments 0

We are going to analyze: does random generator using rand() function in PHP return fair values? Just imagine, each side of coin and dice should have equal probability. So, we want to know if using rand() function to simulate tossing coin or dice was fair enough.

Generating Random Values

We could generate random values by creating a PHP script as follows:

<?php
//random.php
//random.php size min max [outfile]
//
echo "Random Values Generator\n\n";
// 
$argc = $_SERVER['argc'];
$script = $_SERVER['argv'][0];
// 
if ($argc < 4){
	echo "Usage:\n\n";
	echo "{$script} size min max outfile\n\n"
		."\tsize\tNumber/size of figures generated\n"
		."\tmin\tMinimum value\n"
		."\tmax\tMaximum value\n"
		."\toutfile\tOutput filename, default screen\n";
	die;
}
// 
$size = $_SERVER['argv'][1];
$min = $_SERVER['argv'][2];
$max = $_SERVER['argv'][3];
$outfile = @$_SERVER['argv'][4];
// 
$output = "";
for ($i=0; $i<$size; $i++){
	$output .= round(rand($min, $max))."\n";
}
// 
//save to output filename
if ($outfile){
	echo "Writing data to {$outfile} ..";
	if (file_put_contents($outfile, $output)!==FALSE) echo "Success\n";
	else echo "Failed\n";
} else echo str_replace("\n"," ",$output)."\n";

At terminal, we call the script by typing a command as follows to generate one hundred random values laid between 1 to 6.

$ php random.php 1000 1 6

We also could save the output to a file by specified filename

$ php random.php 1000 1 6 sampel.txt

Next, we proceed the output to check if the data generated were fair enough.

Analysing The Fairness

In my cases, I use R Statistics software to analyze the data. Here is the R script:

The histogram of random values displayed as follows:

Seems the data of each number 1-6 was similar with subsequent frequencies 179, 168, 159, 159, 162 and 173. By using ChiSquare Test procedure, we got p-value = 0.8491, high enough, meant all generated random values had equal probabilities.

Conclusion

Yes, we could use rand() function, as data generated by PHP script will follow Uniform Distribution.

Author
Categories PHP, R Statistics

Comments

There are currently no comments on this article.

Comment

Enter your comment below. Fields marked * are required. You must preview your comment before submitting it.






Comments

There are currently no comments on this article.

Comment

Enter your comment below. Fields marked * are required. You must preview your comment before submitting it.