首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >添加到boost::累加器的值的数量是否有限制?

添加到boost::累加器的值的数量是否有限制?
EN

Stack Overflow用户
提问于 2021-01-08 13:34:03
回答 1查看 148关注 0票数 1

对于一个boost::累加器可以添加多少个值有限制吗?如果添加了大量条目,是否存在累加器停止正常工作的点,或者内部算法是否足够健壮,足以考虑一组接近无穷大的值?

代码语言:javascript
复制
#include <iostream>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/moment.hpp>
using namespace boost::accumulators;

int main()
{
    // Define an accumulator set for calculating the mean and the
    // 2nd moment ...
    accumulator_set<double, stats<tag::mean, tag::moment<2> > > acc;

    // push in some data ...
    for (std::size_t i=0; i<VERY_LARGE_NUMBER; i++)
    {
      acc(i);
    }


    // Display the results ...
    std::cout << "Mean:   " << mean(acc) << std::endl;
    std::cout << "Moment: " << moment<2>(acc) << std::endl;

    return 0;
}
EN

回答 1

Stack Overflow用户

发布于 2021-12-07 19:52:12

累加器统计信息不考虑溢出,因此需要仔细选择累加器类型。它不需要匹配您要添加的对象的初始类型--您可以在积累时转换它,然后获取统计数据并将其转换回原始类型。

你可以在这个简单例子上看到它

代码语言:javascript
复制
#include <bits/stdc++.h>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>

using namespace boost::accumulators;

int main(void) {
    accumulator_set<int8_t, features<tag::mean>> accInt8;
    accumulator_set<double, features<tag::mean>> accDouble;
    
    int8_t sum = 0; // range of int8_t: -128 to 127
    for (int8_t i = 1; i <= 100; i++) {
        sum += i; // this will overflow!
        accInt8(i); // this will also overflow
        accDouble((double)i);
    }
    
    std::cout << "sum from 1 to 100: " << (int)sum << " (overflow)\n";
    std::cout << "mean(<int8_t>): " << extract::mean(accInt8) << " (overflow)\n";
    std::cout << "mean(<double>): " << (int)extract::mean(accDouble) << "\n";
    
    return 0;
}

我使用了int8_t,它的范围很小(-128到127),它演示了如果使用int8_t作为accumulator_set的内部类型,从1到100 (应该是50)的平均值就会溢出。

产出如下:

代码语言:javascript
复制
sum from 1 to 100: -70 (overflow)
mean(<int8_t>): -7 (overflow)
mean(<double>): 50
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65629986

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档