3.1-math.js使用
2019-04-30 本文已影响0人
懒羊羊3号
优化数据的计算
https://mathjs.org/docs/reference/functions.html
1、均值,方差,标准差
const x = item.data;
x.sort((a, b) => a - b);
const total = x.length;
const sum = x.reduce((t, n) => t + n);
const min = x[0];
const max = x[total - 1];
const mean = Math.round(sum / total);
let median = 0;
if (total % 2) {
median = x[(total - 1) / 2];
} else {
median = (x[total / 2 - 1] + x[total / 2]) / 2;
}
const stdDevSum = x.map(a => (a - mean) * (a - mean)).reduce((t, n) => t + n);
const stdDev = Math.sqrt(stdDevSum / (total - 1)).toFixed(6);
stats.push([item.name, min, max, mean, median, stdDev]);
math的方法,可以接收arr也可以接收...arr
math.min(x),
math.max(x),
Math.round(math.mean(x)),
Math.round(math.median(x)),
math.std(x).toFixed(6),
2、随机数
math.pickRandom([3, 6, 12, 2]) // returns one of the values in the array
random(100) // 有小数
randomInt(20,25) // 有20没有25