2016-09-21 34 views
0

我有一個數組列表中的數字,我想計算上部圍欄。使用Math.js計算上部圍欄

我知道我必須計算中位數,這可以使用math.js庫來完成。

var median = math.median(numList); 

然後第三個四分位數是中位數的上半部分。我想我會先解決,我相信這可以這樣做,

numList.sort(function(a,b){return a - b}); 

但我不知道如何從這裏着手上計算第三個四分位數和四分位範圍,以獲得上圍欄。

任何幫助,非常感謝。

回答

0

您可以繼續使用中位數,並讓Math.js爲您排序。

function quartileBounds(_sample){ 
    // find the median as you did 
    var _median = math.median(_sample) 

    // split the data by the median 
    var _firstHalf = _sample.filter(function(f){ return f < _median }) 
    var _secondHalf = _sample.filter(function(f){ return f >= _median }) 

    // find the medians for each split 
    var _25percent = math.median(_firstHalf); 
    var _75percent = math.median(_secondHalf); 

    var _50percent = _median; 
    var _100percent = math.max(_secondHalf); 

    // this will be the upper bounds for each quartile 
    return [_25percent, _50percent, _75percent, _100percent]; 
} 

quartileBounds([7,18,33,32,10,30,77,40,135,30,121,36,26,28,60,80,17,288,114]); 
// returns [26,33,78.5,288]