2010-06-23 113 views
1

使用Boost的累加器,我可以輕鬆計算出 加權或未加權輸入集的統計量。我想知道是否可以在同一個累加器內混合加權 和未加權的數量。看看 docs它似乎並不是這樣。使用相同的boost :: accumulator_set計算加權和未加權統計量?

編譯沒有問題,但產生的另一個結果不是我所希望的:

using namespace boost::accumulators; 

const double a[] = {1, 1, 1, 1, 1, 2, 2, 2, 2}; 
const double w[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; 

accumulator_set<double, features<tag::sum, tag::weighted_sum>, double> stats; 
for (size_t i=0; i<9; ++i) 
    stats(a[i], weight = w[i]); 

std::cout << sum(stats) <<" "<< weighted_sum(stats) << std::endl; 
// outputs "75 75" instead of "13 75" 

而且,與第三模板參數accumulator_set我似乎總是 獲得加權量,用「加權」功能,即使和提取:

accumulator_set<double, features<tag::sum>, double> stats; 
for (size_t i=0; i<9; ++i) 
    stats(a[i], weight = w[i]); 
std::cout << sum(stats) << std::endl; 
// outputs "75" instead of 13 

我每次必須使用兩個不同的蓄電池,如果我想計算兩個 加權和不加權量?

編輯 我只是用sum作爲一個例子,在現實中我感興趣的多,更復雜的數量。

回答

0

它在說documentation

當您指定的權重,所有的 蓄電池組中的被替換 與它們的加權當量。

可能有更好的方法來做到這一點,但你可以嘗試這樣的事情(基本上是交換價值的意義與重量):

accumulator_set< double, stats< tag::sum, tag::sum_of_weights >, double > acc; 
const double a[] = {1, 1, 1, 1, 1, 2, 2, 2, 2}; 
const double w[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; 

    for(int i = 0; i < sizeof(a)/sizeof(a[ 0 ]); i++) 
     acc(w[ i ], weight = a[ i ]); 

    std::cout << extract_result<tag::sum>(acc) << std::endl; // weighted sum, prints 75 
    std::cout << extract_result<tag::sum_of_weights>(acc) << std::endl; // sum, prints 13 
+0

謝謝!是的,這對'sum'的情況是有效的。我沒有說清楚這僅僅是一個例子,當我真正有興趣提取其他更復雜的數量時(例如方差,中值和均值以及它們的加權對應數)。總而言之,一開始可能不會使用累加器。 – 2010-06-23 06:02:07

+0

我接受這個答案,因爲它指出了文檔中的明顯的一點。我仍然不知道是否有一些令人討厭的模板技巧來做我想做的事情,但從文檔看來,這似乎需要一個骯髒的黑客,而不是'accumulator_set'直接支持的東西。 – 2010-06-24 00:28:48