ewma.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /*
  2. * compute an Exponential Weighted moving average
  3. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  4. * - heavily inspired from shaka-player
  5. */
  6. class EWMA {
  7. public readonly halfLife: number;
  8. private alpha_: number;
  9. private estimate_: number;
  10. private totalWeight_: number;
  11. // About half of the estimated value will be from the last |halfLife| samples by weight.
  12. constructor(halfLife: number, estimate: number = 0, weight: number = 0) {
  13. this.halfLife = halfLife;
  14. // Larger values of alpha expire historical data more slowly.
  15. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  16. this.estimate_ = estimate;
  17. this.totalWeight_ = weight;
  18. }
  19. sample(weight: number, value: number) {
  20. const adjAlpha = Math.pow(this.alpha_, weight);
  21. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  22. this.totalWeight_ += weight;
  23. }
  24. getTotalWeight(): number {
  25. return this.totalWeight_;
  26. }
  27. getEstimate(): number {
  28. if (this.alpha_) {
  29. const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  30. if (zeroFactor) {
  31. return this.estimate_ / zeroFactor;
  32. }
  33. }
  34. return this.estimate_;
  35. }
  36. }
  37. export default EWMA;