Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 311 and 400] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403]

   1  <?php
   2  
   3  declare(strict_types=1);
   4  
   5  namespace Phpml\Math\Statistic;
   6  
   7  use Phpml\Exception\InvalidArgumentException;
   8  
   9  class StandardDeviation
  10  {
  11      /**
  12       * @param float[]|int[] $numbers
  13       */
  14      public static function population(array $numbers, bool $sample = true): float
  15      {
  16          $n = count($numbers);
  17          if ($n === 0) {
  18              throw new InvalidArgumentException('The array has zero elements');
  19          }
  20  
  21          if ($sample && $n === 1) {
  22              throw new InvalidArgumentException('The array must have at least 2 elements');
  23          }
  24  
  25          $mean = Mean::arithmetic($numbers);
  26          $carry = 0.0;
  27          foreach ($numbers as $val) {
  28              $carry += ($val - $mean) ** 2;
  29          }
  30  
  31          if ($sample) {
  32              --$n;
  33          }
  34  
  35          return ($carry / $n) ** .5;
  36      }
  37  
  38      /**
  39       * Sum of squares deviations
  40       * ∑⟮xᵢ - μ⟯²
  41       *
  42       * @param float[]|int[] $numbers
  43       */
  44      public static function sumOfSquares(array $numbers): float
  45      {
  46          if (count($numbers) === 0) {
  47              throw new InvalidArgumentException('The array has zero elements');
  48          }
  49  
  50          $mean = Mean::arithmetic($numbers);
  51  
  52          return array_sum(array_map(
  53              function ($val) use ($mean) {
  54                  return ($val - $mean) ** 2;
  55              },
  56              $numbers
  57          ));
  58      }
  59  }