当我使用boost::accumulators::statistics来计算数组的中位数时,我得到了以下代码和结果:
accumulator_set< double, features< tag::mean, tag::median > > acc;
acc(2);
acc(1);
acc(3);
value = mean( acc ); //output is 2, expected
value = median( acc ); //output is 3, unexpected我认为value = median( acc )的结果应该是2。
发布于 2019-03-17 22:58:14
accumulator_set实际上并不存储所有的值。每次对acc(double)的调用实际上都会调用类似于acc.mean_accumulator(double); acc.median_accumulator(double)的东西,并且它尽量不存储所有的值。
对于median,使用P^2分位数估计器。(See here)这只是一个估计,如果你这样做了:
acc(4);
acc(1);
acc(2);
acc(0);
acc(3);它返回预期的2。
如果您想要一个精确值并且只有少量的数据值,请使用如下所示的函数:
#include <algorithm>
#include <vector>
// Warning: Will swap elements in the range.
// `It` needs to be a non-const random access iterator
// (Like `T*`)
template<class It>
auto median(It first, It last) {
auto size = last - first;
if (size % 2 == 1U) {
std::nth_element(first, first + (size / 2U), last);
return *(first + (size / 2U));
}
std::nth_element(first, first + (size / 2U), last);
auto&& high = first + (size / 2U);
auto&& low = std::max(first, first + (size / 2U - 1U));
return (*low + *high) / 2;
}
// Copies the range and modifies the copy instead
template<class It>
auto const_median(It first, It last) {
std::vector<decltype(*first)> v(first, last);
return median(v.begin(), v.end());
}
int main() {
std::vector<double> v{2, 1, 3};
std::cout << median(v.begin(), v.end()) << '\n';
}https://stackoverflow.com/questions/55204608
复制相似问题