Chi Square Probability Distribution Code Using PHP

By | September 18, 2012

This example is a Web application piece of code that I wrote to add a (approximate) p-value to some dynamically generated crosstabs.  This will allow a researcher to provide a way to deliver data over the web and will allow the researcher a way to calculate the p-value from a \chi^{2} distribution based on input data.  In order to use this function the researcher must calculate the \chi^{2} value first by using the standard \chi^{2} equation: \sum \frac{ \left( O - E \right)^{2} }{E}.  In addition to the \chi^{2} statistic the researcher needs to provide the degrees of freedom.

function getChiSquare($x, $n) {
if ( ($n==1) && ($x > 1000) ) {
return 0;
}

if ( ($x>1000) || ($n>1000) ) {
$q = getChiSquare(($x-$n)*($x-$n)/(2*$n),1) / 2;
if($x > $n) {
return $q;
} else {
return 1 - $q;
}
}
$p = exp(-0.5 * $x);
if(($n % 2) == 1) {
$p = $p * sqrt(2*$x/pi());
}
$k = $n;
while($k >= 2) {
$p = $p * ($x/$k);
$k = $k - 2;
}
$t = $p;
$a = $n;
while($t > 0.0000000001 * $p) {
$a = $a + 2;
$t = $t * ($x / $a);
$p = $p + $t;
}

$retval = 1-$p;
return $retval;
}

Category: Uncategorized

3 thoughts on “Chi Square Probability Distribution Code Using PHP

  1. annotated

    “…In order to use this function the researcher must calculate…”

    How about providing the WHOLE formula, useless.

    Reply
  2. Paris Char

    Amazing! exactly equivalent to excel’s CHISQ.DIST.RT function. Thank you!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *