[R] R: to the power

(Ted Harding) Ted.Harding at nessie.mcc.ac.uk
Sat Jul 16 11:44:18 CEST 2005


On 16-Jul-05 Bernardo Rangel Tura wrote:
> At 10:11 12/7/2005, allan_sta_staff_sci_main_uct at mail.uct.ac.za wrote:
>>hi all
>>
>>why does R do this:
>>
>>(-8)^(1/3)=NaN
>>
>>the answer should be : -2
> 
> Allan
> 
> In my computer:
>  > (-8)^(1/3)
> [1] NaN
> 
>  > -8^(1/3)
> [1] -2
> 
>  > -(8^(1/3))
> [1] -2
> 
> 
> The problem is -8 or the problem is (-8) ?
> 
> 
> []s
> Tura 

There's no problem. The issue lies in implicit precedence.
See ?Syntax.

In (-8)^(1/3) you have used parentheses to force evaluation
of "-3" and of "1/3" prior to applying "^", and "^" to a fraction
gives NaN for negative numbers.

In -8^(1/3) the parentheses force evaluation of (1/3) before
it is used as the "power" in "^", but implicit precedence
(see ?Syntax) causes "^" to be applied before "-" is applied.

So the result is equivalent to

  -(8^(1/3))

i.e. the same as your third case.

When you're not sure about the order in which operations will
be carried out, use parentheses to ensure that the precedence
you want is the one you will get. Otherwise you could get a
result like

  > -8^1/3
  [1] -2.666667

which equals  (-(8^1))/3, when you really wanted -(8^(1/3)).

Best wishes,
Ted.


--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 16-Jul-05                                       Time: 10:43:58
------------------------------ XFMail ------------------------------




More information about the R-help mailing list