从整数向量中获取平均值 [英] Get the average value from a vector of Integers

查看:22
本文介绍了从整数向量中获取平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直无法找到一种从 C++ 中的整数向量获取平均值的方法.

I have been unable to find a way of getting the average value from a vector of integers in C++.

我不可能开始添加所有值,因为我可能会超过可接受的最大整数值.

I can't possibly start adding all of the values because I could exceed the maximum integer accepted value.

如何高效快速地计算?C++ 语言中是否有任何标准库可以做到这一点?

How can I calculate this efficiently and quickly ? Are there any standard libraries in the C++ language to do that ?

推荐答案

首选方法只是使用 std::accumulate:

The go-to approach is just summing with a sufficiently wide integer type with std::accumulate:

double avg1(std::vector<int> const& v) {
    return 1.0 * std::accumulate(v.begin(), v.end(), 0LL) / v.size();
}

如果这个总和溢出(有 2300 万个整数,平均值必须至少为 4.01x1011 - 也就是说,它不会溢出,因为这甚至不适合 int32_t ......所以你很好,但如果你得到几个数量级的数字,或者有更宽的 int type),那么你可以改用常见的在线"算法来计算均值:

If this sum overflows (with 23 million ints, the average would have to be at least 4.01x1011 - which is to say, it won't overflow since that won't even fit in an int32_t... so you're way good, but on the off chance you get several orders of magnitude more numbers, or have wider a int type), then you can instead use the common "online" algorithm for calculating the mean:

double avg2(std::vector<int> const& v) {
    int n = 0;
    double mean = 0.0;
    for (auto x : v) {
        double delta = x - mean;
        mean += delta/++n;
    }
    return mean;
}

这不会溢出,不会很容易丢失精度,但由于重复的额外除法,可能会更昂贵.

This won't overflow, isn't very prone to loss of precision, but may be more expensive due to repeated extra divisions.

这篇关于从整数向量中获取平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆