Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.
   1  <?php
   2  
   3  declare(strict_types=1);
   4  
   5  namespace Phpml\Math\Statistic;
   6  
   7  use Phpml\Exception\InvalidArgumentException;
   8  
   9  class Correlation
  10  {
  11      /**
  12       * @param int[]|float[] $x
  13       * @param int[]|float[] $y
  14       *
  15       * @throws InvalidArgumentException
  16       */
  17      public static function pearson(array $x, array $y): float
  18      {
  19          if (count($x) !== count($y)) {
  20              throw new InvalidArgumentException('Size of given arrays does not match');
  21          }
  22  
  23          $count = count($x);
  24          $meanX = Mean::arithmetic($x);
  25          $meanY = Mean::arithmetic($y);
  26  
  27          $axb = 0;
  28          $a2 = 0;
  29          $b2 = 0;
  30  
  31          for ($i = 0; $i < $count; ++$i) {
  32              $a = $x[$i] - $meanX;
  33              $b = $y[$i] - $meanY;
  34              $axb += ($a * $b);
  35              $a2 += $a ** 2;
  36              $b2 += $b ** 2;
  37          }
  38  
  39          return $axb / ($a2 * $b2) ** .5;
  40      }
  41  }