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 distribution based on input data. In order to use this function the researcher must calculate the value first by using the standard equation: . In addition to the 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; }

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

How about providing the WHOLE formula, useless.

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

Thank you for making this available!