[R] geometric mean to handle large number and negative values

Richard.Cotton at hsl.gov.uk Richard.Cotton at hsl.gov.uk
Wed Apr 15 12:27:36 CEST 2009


> > > geometric.mean1 <- function(x) prod(x)^(1/length(x))
> > > geometric.mean2 <- function(x) exp(mean(log(x)))
> > > geometric.mean1(c(-5,-4,4,5))
> > [1] 4.472136
> > > geometric.mean2(c(-5,-4,4,5))
> > [1] NaN
> > Warning message:
> > In log(x) : NaNs produced

> comp.x <- as.complex(c(-5,-4,4,5))
> geometric.mean2(comp.x)
> # [1] 0+4.472136i

Obviously, there's a discrepancy between the answer of geometric.mean1 and 
geometric.mean2 with complex inputs.  Having thought about it a little 
more, I think the problem is with my solution.

The log of a complex number decomposes as log(z) = log(abs(z)) +1i*Arg(z). 
 When you sum the second components, you need to take the answer modulo 
2*pi, since the phase angles wrap around.

Here's an alternative geometric mean function that takes that into 
account.

geometric.mean3 <- function(x) 
{
   a <- mean(log(abs(x)))
   b <- 1i/length(x) 
   c <- sum(Arg(x))%%(2*pi)
   exp(a+b*c)
}

geometric.mean3(comp.x)
# [1] 4.472136+0i

Regards,
Richie.

Mathematical Sciences Unit
HSL


------------------------------------------------------------------------
ATTENTION:

This message contains privileged and confidential inform...{{dropped:20}}




More information about the R-help mailing list