Efficient way to compute geometric mean of many numbers

前端 未结 7 1073
栀梦
栀梦 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:29

    Instead of using logarithms, which are very expensive, you can directly scale the results by powers of two.

    double geometric_mean(std::vector const&data) {
      double huge = scalbn(1,512);
      double tiny = scalbn(1,-512);
      int scale = 0;
      double product = 1.0;
      for(auto x:data) {
        if (x >= huge) {
          x = scalbn(x, -512);
          scale++;
        } else if (x <= tiny) {
          x = scalbn(x, 512);
          scale--;
        }
        product *= x;
        if (product >= huge) {
          product = scalbn(product, -512);
          scale++;
        } else if (product <= tiny) {
          product = scalbn(product, 512);
          scale--;
        }
      }
      return exp2((512.0*scale + log2(product)) / data.size());
    }
    

提交回复
热议问题