Since the product of a large number of numbers can get unreasonably large, it is probably generally best to compute the geometric mean as the exponential of the ordinary arithmetic mean of the logarithms of the numbers.
The C++ standard library provides log
for natural logarithm and exp
for exponentation with base e . Thus:
#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 );
}
Instead of the loop you can use std::accumulate
.
Disclaimer: code untouched by compiler's hands.
You can do this pow(x, 1.0/m)
. It is same with m. root.
Use the following:
#include <cmath>
...
double nth_root = std::pow(number, 1.0 / n);
https://en.wikipedia.org/wiki/Nth_root
m
is the degree of the root, the product under it the radicand.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.