我承认我不是C++专家。
我正在寻找一种计算Boost中位数的加权中位数的快速方法。
但似乎我无法使其工作。
#include <iostream>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/median.hpp>
#include <boost/accumulators/statistics/weighted_median.hpp>
using namespace boost::accumulators;
int main()
{
// Define an accumulator set
accumulator_set<double, stats<tag::median > > acc1;
accumulator_set<double, stats<tag::median >, float> acc2;
// push in some data ...
acc1(0.1);
acc1(0.2);
acc1(0.3);
acc1(0.4);
acc1(0.5);
acc1(0.6);
acc2(0.1, weight=0.);
acc2(0.2, weight=0.);
acc2(0.3, weight=0.);
acc2(0.4, weight=1.);
acc2(0.5, weight=1.);
acc2(0.6, weight=1.);
// Display the results ...
std::cout << " Median: " << median(acc1) << std::endl;
std::cout << "Weighted Median: " << median(acc2) << std::endl;
return 0;
}
产生以下输出,这显然是错误的。
Median: 0.3
Weighted Median: 0.3
难道我做错了什么?
任何帮助将不胜感激。
*但是,加权总和可以正常工作*
@glowcoder:加权总和可以像这样完美地工作。
#include <iostream>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/sum.hpp>
#include <boost/accumulators/statistics/weighted_sum.hpp>
using namespace boost::accumulators;
int main()
{
// Define an accumulator set
accumulator_set<double, stats<tag::sum > > acc1;
accumulator_set<double, stats<tag::sum >, float> acc2;
// accumulator_set<double, stats<tag::median >, float> acc2;
// push in some data ...
acc1(0.1);
acc1(0.2);
acc1(0.3);
acc1(0.4);
acc1(0.5);
acc1(0.6);
acc2(0.1, weight=0.);
acc2(0.2, weight=0.);
acc2(0.3, weight=0.);
acc2(0.4, weight=1.);
acc2(0.5, weight=1.);
acc2(0.6, weight=1.);
// Display the results ...
std::cout << " Median: " << sum(acc1) << std::endl;
std::cout << "Weighted Median: " << sum(acc2) << std::endl;
return 0;
}
结果是
Sum: 2.1
Weighted Sum: 1.5
最佳答案
boost 功能未损坏。
问题在于您没有提供足够的数据来使P ^ 2估计器起作用。如果围绕数据输入(例如)
for(int i=0;i<100000;i++){
acc2(0.1, weight=0.);
acc2(0.2, weight=0.);
acc2(0.3, weight=0.);
acc2(0.4, weight=1.);
acc2(0.5, weight=1.);
acc2(0.6, weight=1.);
}
您得到正确的结果
Median: 0.3
Weighted Median: 0.5
或者,您可以指定
accumulator_set<double,
stats<tag::weighted_median(with_p_square_cumulative_distribution) >,
double> acc2 ( p_square_cumulative_distribution_num_cells = 5 );
即使您的问题中仅添加了6点,它也给出了
Weighted Median: 0.55
作为答案。关于c++ - Boost Library的加权中位数被打破了吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5111304/