queue_stats-8.x-1.0-beta1/src/Statistics/ExponentialMovingAverage.php
src/Statistics/ExponentialMovingAverage.php
<?php
namespace Drupal\queue_stats\Statistics;
/**
* Exponential moving average.
*
* This allows us to store only previous averages and number of items instead
* of individual values.
*/
class ExponentialMovingAverage {
/**
* The number of items which the statistics are based on.
*
* @var int
*/
protected $numItems = 0;
/**
* The average.
*
* @var float
*/
protected $average = 0;
/**
* The exponential weighted moving average factor.
*
* This is a constant that affects how quickly the average "catches up" to the
* latest trend. Smaller the number the faster. (At 1 it's no longer an
* average and just becomes the latest value.)
*
* @var int
*/
protected $factor;
/**
* ExponentialMovingAverage constructor.
*
* @param int $factor
* The exponential weighted moving average factor.
*/
public function __construct(int $factor) {
$this->factor = $factor;
}
/**
* Adds a value to the exponential moving average.
*/
public function add($value) {
$this->numItems++;
$this->average = $this->average + (($value - $this->average) / min($this->factor, $this->numItems));
return $this->average;
}
/**
* Returns the exponential moving average.
*
* @return float
* The exponential moving average.
*/
public function average() {
return $this->average;
}
}
