由于大量数字的乘积可能变得过大,因此通常最好将几何平均值计算为数字对数的普通算术平均值的指数.
C++标准库提供log自然对数和exp基数e的指数.从而:
#include <math.h>
auto geometric_mean( double const* const first, double const* const past_end )
-> double
{
double sum = 0;
for( double const* p = first; p != past_end; ++p )
{
sum += log( *p );
}
const int n = past_end - first;
return exp( sum/n );
}
Run Code Online (Sandbox Code Playgroud)
而不是你可以使用的循环std::accumulate.
免责声明:编码器手中没有触及代码.
| 归档时间: |
|
| 查看次数: |
106 次 |
| 最近记录: |