php教程

stats_covariance

(PECL stats >= 1.0.0)

stats_covarianceComputes the covariance of two data sets

说明

stats_covariance ( array $a , array $b ) : float

Returns the covariance of a and b.

参数

a

The first array

b

The second array

返回值

Returns the covariance of a and b, or FALSE on failure.

User Contributed Notes

Angel J. Salinas 22-Dec-2015 09:37
// kanniprabu's function is wrong.
// You can check this function with COVARIANCE.P Excel function:

function getCovariance( $valuesA, $valuesB )
{
  $countA = count($valuesA);
  $countB = count($valuesB);
  if ( $countA != $countB ) {
    trigger_error( 'Arrays with different sizes: countA='. $countA .', countB='. $countB, E_USER_WARNING );
    return false;
  }

  if ( $countA < 0 ) {
    trigger_error( 'Empty arrays', E_USER_WARNING );
    return false;
  }

  // Use library function if available
  if ( function_exists( 'stats_covariance' ) ) {
    return stats_covariance( $valuesA, $valuesB );
  }

  $meanA = array_sum( $valuesA ) / floatval( $countA );
  $meanB = array_sum( $valuesB ) / floatval( $countB );
  $add = 0.0;

  for ( $pos = 0; $pos < $countA; $pos++ ) {
    $valueA = $valuesA[ $pos ];
    if ( ! is_numeric( $valueA ) ) {
      trigger_error( 'Not numerical value in array A at position '. $pos .', value='. $valueA, E_USER_WARNING );
      return false;
    }

    $valueB = $valuesB[ $pos ];
    if ( ! is_numeric( $valueB ) ) {
      trigger_error( 'Not numerical value in array B at position '. $pos .', value='. $valueB, E_USER_WARNING );
      return false;
    }

    $difA = $valueA - $meanA;
    $difB = $valueB - $meanB;
    $add += ( $difA * $difB );
  } // for

  return $add / floatval( $countA );
}
kanniprabu at gmail dot com 16-Mar-2013 10:30
<?php
   
//Covariance Calculation
   
function standard_covariance($aValues,$bValues)
    {
       
$a= (array_sum($aValues)*array_sum($bValues))/count($aValues);
       
$ret = array();
        for(
$i=0;$i<count($aValues);$i++)
        {
           
$ret[$i]=$aValues[$i]*$bValues[$i];
        }
       
$b=(array_sum($ret)-$a)/(count($aValues)-1);       
        return (float)
$b;
    }
   
$aValues=array(3,4,5,7);       
   
$bValues=array(10,11,13,14);
    echo
standard_covariance($aValues,$bValues);   
?>

CopyRight © 2008-2022 verySource.Com All Rights reserved. 京ICP备17048824号-1 京公网安备:11010502034788