开发者

php statistics z-score normal distributions

开发者 https://www.devze.com 2023-03-31 03:49 出处:网络
how do I compute the z-score of a array of numbers using PHP? 开发者_高级运维I need to compute the z-score and then find the percentile (CDF)! what PHP functions can I use? thanks!The following code w

how do I compute the z-score of a array of numbers using PHP? 开发者_高级运维I need to compute the z-score and then find the percentile (CDF)! what PHP functions can I use? thanks!


The following code will give a good approximation of the CDF (Abramowitz & Stegun (1964))

function normal_pdf($x) {
    return exp(-$x * $x / 4) / sqrt(2 * M_PI);
}

function normal_cdf($x) {
    $b = array(0.2316419, 0.319381530, -0.356563782, 1.781477937, -1.821255978, 1.330274429);
    $t = 1 / (1 + $b[0] * $x);
    $result = 0;
    for ($i = 1; $i < 6; $i++) {
        $result += $b[$i] * pow($t, $i);
    }
    return 1 - normal_pdf($x) * $result;
}

This assumes a standard normal distribution. Recall that to standardize, use z = (x - mean) / (standard deviation)


/* Mean */
function mean($input_array)
{
  $total = 0;
  foreach ($input_array as $value)
  {
    $total += $value;
  }
  return ($total / count($input_array));
}

/* Standard Deviation */
function std($arr)
{
  if (!count($arr))
  return 0;
  $mean = mean($arr);
  $sos = 0; // Sum of squares
  for ($i = 0; $i < count($arr); $i++)
  {
    $sos += ($arr[$i] - $mean) * ($arr[$i] - $mean);
  }
  return sqrt($sos / (count($arr) - 1));
}

/* Z Scores */
function z($var, $arr)
{
  return ($var -mean($arr)) / std($arr);
}


There are a few functions in the PHP statistics extension that could help you — You probably want stats_standard_deviation for a start.


$control=array(15,7);
$treatment=array(46,8);
$confidence=number_format(cumnormdist(zscore($control, $treatment))*100,0);   

function cr($t) 
{ 
    return $t[1]/$t[0]; 
}

function zscore($c, $t) 
{
    $z = cr($t)-cr($c);
    $s = (cr($t)*(1-cr($t)))/$t[0] + (cr($c)*(1-cr($c)))/$c[0];
    return $z/sqrt($s);
}

function cumnormdist($x)
{
  $b1 =  0.319381530;
  $b2 = -0.356563782;
  $b3 =  1.781477937;
  $b4 = -1.821255978;
  $b5 =  1.330274429;
  $p  =  0.2316419;
  $c  =  0.39894228;

  if($x >= 0.0) {
      $t = 1.0 / ( 1.0 + $p * $x );
      return (1.0 - $c * exp( -$x * $x / 2.0 ) * $t *
      ( $t *( $t * ( $t * ( $t * $b5 + $b4 ) + $b3 ) + $b2 ) + $b1 ));
  }
  else {
      $t = 1.0 / ( 1.0 - $p * $x );
      return ( $c * exp( -$x * $x / 2.0 ) * $t *
      ( $t *( $t * ( $t * ( $t * $b5 + $b4 ) + $b3 ) + $b2 ) + $b1 ));
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号