gpt4 book ai didi

javascript - 如何使用 reduce() 求均值和方差?

转载 作者:行者123 更新时间:2023-11-30 12:16:03 26 4
gpt4 key购买 nike

我编写了一个函数,它仅使用 reduce() 返回给定列表的均值和方差。

    var list = [1, 2, 3, 4];

var math = getMeanAndVar(list);

function getMeanAndVar(list) {

var res = list.reduce(function(lis, cur, ind, arr) {

var meanTot = arr.reduce(function(pre, cur) {
return pre + cur;
})
var total = getVariance(arr, tot / arr.length);
return {
mean: meanTot / arr.length,
variance: total / arr.length
}

function getVariance(list, mean) {
return list.reduce(function(pre, cur) {
pre = pre + Math.pow((cur - mean), 2);
return pre;
}, 0)
}
})
return ["Mean:",
res.mean,
"Variance:",
res.variance
].join(' ');
}
console.log(math);

还有其他优化代码的方法吗?

最佳答案

去掉外层的reduce。这是没用的。考虑一下:

function getMeanAndVar(arr) {

function getVariance(arr, mean) {
return arr.reduce(function(pre, cur) {
pre = pre + Math.pow((cur - mean), 2);
return pre;
}, 0)
}

var meanTot = arr.reduce(function(pre, cur) {
return pre + cur;
})
var total = getVariance(arr, meanTot / arr.length);

var res = {
mean: meanTot / arr.length,
variance: total / arr.length
}

return ["Mean:",
res.mean,
"Variance:",
res.variance
].join(' ');
}

var arr = [1, 2, 3, 4];

var math = getMeanAndVar(arr);

console.log(math);'

打印:

Mean: 2.5 Variance: 1.25

关于javascript - 如何使用 reduce() 求均值和方差?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32394390/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com