Efficient way to compute geometric mean of many numbers

前端 未结 7 1068
栀梦
栀梦 2020-12-14 07:12

I need to compute the geometric mean of a large set of numbers, whose values are not a priori limited. The naive way would be

double geometric_mean(std::vect         


        
7条回答
  •  佛祖请我去吃肉
    2020-12-14 07:43

    Summing logs to compute products stably is perfectly fine, and rather efficient (if this is not enough: there are ways to get vectorized logarithms with a few SSE operations -- there are also Intel MKL's vector operations).

    To avoid overflow, a common technique is to divide every number by the maximum or minimum magnitude entry beforehand (or sum log differences to the log max or log min). You can also use buckets if the numbers vary a lot (eg. sum the log of small numbers and large numbers separately). Note that typically neither of this is needed except for very large sets since the log of a double is never huge (between say -700 and 700).

    Also, you need to keep track of the signs separately.

    Computing log x keeps typically the same number of significant digits as x, except when x is close to 1: you want to use std::log1p if you need to compute prod(1 + x_n) with small x_n.

    Finally, if you have roundoff error problems when summing, you can use Kahan summation or variants.

提交回复
热议问题