• PHP Video Tutorials

PHP - Stats Covariance() Function



Definition and Usage

The stats_covariance() function can compute the covariance of two data sets. Covariance is a measure which computes how much two random variables vary together.

Syntax

float stats_covariance( array $a, array $b )

Parameters

Sr.No Parameter Description
1

a

The first array

2

b

The second array

Return Values

The stats_covariance() function can return the covariance of arrays a and b, or false on failure.

Dependencies

This function was first introduced in statistics extension (PHP 4.0.0 and PEAR 1.4.0). We have used latest release of stats-2.0.3 (PHP 7.0.0 or newer and PEAR 1.4.0 or newer) for this tutorial.

Example

In the following example, we compute co-variance of arrays a and b.

<?php
   $a = array(15, 16, 8, 6, 15, 12, 12, 18, 12, 20, 12, 14);

   $b = array(17.24, 15, 14.91, 4.5, 18, 6.29, 19.23, 18.69, 7.21, 42.06, 7.5, 8);

   var_dump(stats_covariance($a_1, $a_2));
?>

Output

This will produce following result −

float(25.460555555556)

Example

Following is an error case. In the following example, we pass two arrays with different sizes. A warning is displayed in logs.

<?php
   var_dump(stats_covariance(array(2,1), array(1))); //arrays not of same size
?>

Output

This will produce following result and a warning in logs PHP Warning: stats_covariance(): The datasets are not of the same size

bool(false)

Example

Following is an error case. In the following example, we pass two arrays with one having zero elements. A warning is displayed in logs.

<?php
   var_dump(stats_covariance(array(), array(0))); //first array with zero elements
?>

Output

This will produce following result and a warning in logs PHP Warning: stats_covariance(): The first array has zero elements

bool(false)
Advertisements