estatistica.js 777 B

123456789101112131415161718192021
  1. export function media(valores) {
  2. return valores.reduce((a, b) => a + b, 0) / valores.length;
  3. }
  4. export function desvioPadrao(valores) {
  5. if (valores.length < 2) return 0;
  6. const m = media(valores);
  7. const variancia = media(valores.map((v) => (v - m) ** 2));
  8. return Math.sqrt(variancia);
  9. }
  10. export function correlacaoPearson(xs, ys) {
  11. if (xs.length < 2 || xs.length !== ys.length) return null;
  12. const mx = media(xs);
  13. const my = media(ys);
  14. const numerador = xs.reduce((soma, x, i) => soma + (x - mx) * (ys[i] - my), 0);
  15. const denomX = Math.sqrt(xs.reduce((soma, x) => soma + (x - mx) ** 2, 0));
  16. const denomY = Math.sqrt(ys.reduce((soma, y) => soma + (y - my) ** 2, 0));
  17. if (denomX === 0 || denomY === 0) return null;
  18. return numerador / (denomX * denomY);
  19. }