Efficient way to compute geometric mean of many numbers

前端 未结 7 1059
栀梦
栀梦 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条回答
  • A different approach which would give better accuracy and performance than the logarithm method would be to compensate out-of-range exponents by a fixed amount, maintaining an exact logarithm of the cancelled excess. Like so:

    const int EXP = 64; // maximal/minimal exponent
    const double BIG = pow(2, EXP); // overflow threshold
    const double SMALL = pow(2, -EXP); // underflow threshold
    
    double product = 1;
    int excess = 0; // number of times BIG has been divided out of product
    
    for(int i=0; i<n; i++)
    {
        product *= A[i];
        while(product > BIG)
        {
            product *= SMALL;
            excess++;
        }
        while(product < SMALL)
        {
            product *= BIG;
            excess--;
        }
    }
    
    double mean = pow(product, 1.0/n) * pow(BIG, double(excess)/n);
    

    All multiplications by BIG and SMALL are exact, and there's no calls to log (a transcendental, and therefore particularly imprecise, function).

    0 讨论(0)
提交回复
热议问题