0

I have an array of four numbers, something like [597103978, 564784412, 590236070, 170889704] and I need to make sure that the variance is no more than 10%, for example for the array above, the check must fail because of the number 170889704.

Can someone suggest me a good method how to do that is Javascript?

Thanks in advance!

  • 1
    do you speak in statisitcs terms or just from the min and max absolute change in percent? what ahve you tried? – Nina Scholz Dec 18 '21 at 18:27
  • Have you searched the web for examples? https://www.tutorialspoint.com/calculating-variance-for-an-array-of-numbers-in-javascript – Wyck Dec 18 '21 at 18:29
  • @NinaScholz I am making a crypto mining stats app, lets say I have stats for 10000 miners. The API only provides me 6h average hashrates and I need to calculate 24h average reward scale for all miners. To keep it as precise as possible, I need to kick out miners with unstable hashrate (if the variance is more than 10% in the last four 6 hour stats). – Michal Doubek Dec 18 '21 at 18:39
  • @Wyck Yeah i tried this, but it only gives variance as a final number, I need percentage. – Michal Doubek Dec 18 '21 at 18:39
  • How would this work with [1, 1, 1, 100000]. All four values would have a large variance, and so all would need to be rejected. But that seems wrong, as you would only want to kick the outlier. If not, please provide the definition of variance you use. – trincot Dec 18 '21 at 19:00

1 Answers1

0

I would do it using Array.every

const arr = [597103978, 564784412, 590236070, 170889704];

const variance = (n, m) => {
  return Math.abs( (n - m) / n );
};

const isLessThanTenPercent = (n) => {
  return ( n < 0.1 );
};

const arrayIsGood = arr.every((n, i) => {

  // m is the next element after n
  const m = arr[i+1];
  if (Number.isInteger(m)) {
    const v = variance(n, m);
    return isLessThanTenPercent(v);
  } else {
    // if m is not an integer, we're at the last element
    return true;
  }

});

console.log({arrayIsGood});
code_monk
  • 9,451
  • 2
  • 42
  • 41