最佳答案
由于大量数字的乘积可能会变得异常大,通常最好将几何平均值计算为数字对数的普通算术平均值的指数。
C++ 标准库提供用于自然对数的log
和用于以e 为底的指数的exp
。因此:
#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 );
}
您可以使用 std::accumulate
代替循环。
免责声明:代码未经编译器处理。
关于c++ - 是否有其他订单的平方根函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35716582/