如何使用reduce()找到均值和方差?

时间:2015-09-04 09:18:26

标签: javascript

我写了一个函数,它只使用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);

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

1 个答案:

答案 0 :(得分:3)

摆脱外部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