Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.
   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  }