[R] Calculating the power of a negative number

Peter Dalgaard P.Dalgaard at biostat.ku.dk
Tue Nov 17 17:28:19 CET 2009


Zhiyuan Jason ZHENG wrote:
> Hello,
> 
>  
> 
> I use R a lot, one thing bugs me is that when I try the following 
> 
>> x<- -8
> 
>> x^(1/3)
> 
> [1] NaN
> 
>  
> 
> However, it is fine with -8^(1/3). Priority goes to the power. Can you help
> me out for this? Thanks.

Well,

mycuberoot <- function(x) sign(x)*abs(x)^(1/3)

but in general there is just no solution. The problem is that for the
solution to be even defined, the power needs to be a fraction with an
odd denominator. With floating point arithmetic and roundoff and what
not, there is just no way to know whether that is the case or not. In
fact, the machine representation of ANY number with a fractional part
will be a fraction with an EVEN denominator (2^{p} for some p).

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)              FAX: (+45) 35327907




More information about the R-help mailing list