Chi-square (χ2) test on PHP's mt_rand() generated numbers
The code
<?php
set_time_limit(0);
// CONFIG
// numerosita' campione = 10^9
$n = 1000000000;
// numero classi = 10
$n_classi = 10;
// probabilita' teorica = 1/10
$p = 1 / $n_classi;
// numeri ripetizioni test chi-quadro
$test_tot = 10;
$mean_value = 0;
for ($ntest = 0; $ntest < $test_tot; $ntest++) {
// BUFFERS
$value = 0;
// n = 10^9
$n = 1000000000;
$np = 0;
// frequenze osservate, 10 classi
$X = array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
$V = array();
for ($i = 0; $i < $n; $i++) {
$s = mt_rand(0, 100);
if (($s < 10) and ($s >= 0))
$X[0]++;
if (($s < 20) and ($s >= 10))
$X[1]++;
if (($s < 30) and ($s >= 20))
$X[2]++;
if (($s < 40) and ($s >= 30))
$X[3]++;
if (($s < 50) and ($s >= 40))
$X[4]++;
if (($s < 60) and ($s >= 50))
$X[5]++;
if (($s < 70) and ($s >= 60))
$X[6]++;
if (($s < 80) and ($s >= 70))
$X[7]++;
if (($s < 90) and ($s >= 80))
$X[8]++;
if (($s < 100) and ($s >= 90))
$X[9]++;
}
$n = 0;
for ($i = 0; $i < $n_classi; $i++) {
$n += $X[$i];
}
$np = $n * $p;
for ($i = 0; $i < $n_classi; $i++) {
$value += ($X[$i] * $X[$i]) / $np;
}
$value -= $n;
$mean_value += $value;
array_push($V, $value);
echo $ntest + 1 . " - test chi-quadro: $value (su $n numeri generati)\n";
}
$mean_value *= 1 / $test_tot;
echo "\n\nMedia valori: $mean_value\n";
?>
The result
1 - test chi-quadro: 10.619749069214 (su 990100610 numeri generati) 2 - test chi-quadro: 6.7322152853012 (su 990097601 numeri generati) 3 - test chi-quadro: 16.159699082375 (su 990091759 numeri generati) 4 - test chi-quadro: 4.0619201660156 (su 990099242 numeri generati) 5 - test chi-quadro: 10.107972741127 (su 990100999 numeri generati) 6 - test chi-quadro: 7.2343780994415 (su 990098289 numeri generati) 7 - test chi-quadro: 7.2346715927124 (su 990102247 numeri generati) 8 - test chi-quadro: 6.4530498981476 (su 990092764 numeri generati) 9 - test chi-quadro: 5.1203221082687 (su 990100214 numeri generati) 10 - test chi-quadro: 7.6798456907272 (su 990096158 numeri generati) Media valori: 8.140382373333 Max: 16.159699082375 Min: 4.0619201660156
This goodness-of-fit test is acceptable because every computation is < χ20.05, 9 < 16.919 (α = 0.05).