[R] cube root of a negative number

Spencer Graves spencer.graves at structuremonitoring.com
Wed Oct 27 02:18:56 CEST 2010


install.packages('sos')# if you don't have it already
library(sos)
rs <- ???roots
# 216 matches
summary(rs)
# in 106 packages
rs # opens a web browser with all 216 matched in a table
# listing the package with the most matches first.

# This included roots{signal}, which referenced polyroot{base},
# which led me to the following:


 > polyroot(c(4, 0, 0, 1))
[1]  0.793701+1.37473i -1.587401+0.00000i  0.793701-1.37473i

 > polyroot(c(4, 0, 1))
[1] 0+2i 0-2i


       Hope this helps.
       Spencer
# please excuse:  I'm the lead author of "sos".  In my not-so-humble 
opinion, it's the fastest way to do a literature search for anything 
statistical.  If your search with "writeFindFn2lxs" does NOT answer your 
question in a very few minutes, it's OK to look elsewhere.  (Please see 
the vignette for more details if you are not familiar with it.)


On 10/26/2010 4:34 PM, Bill.Venables at csiro.au wrote:
> To take it one step further:
>
>> x<- as.complex(-4)
>> cx<- x^(1/3)
>>
>> r<- complex(modulus = Mod(cx), argument = Arg(cx)*c(1,3,5))
>> r
> [1]  0.793701+1.37473i -1.587401+0.00000i  0.793701-1.37473i
>> r^3
> [1] -4+0i -4+0i -4+0i
> So when you ask for "the" cube root of -4, R has a choice of three possible answers it can give you.
>
> It is no surprise that this does not work when working in the real domain, except "by fluke" with something like
>
>> -4^(1/3)
> [1] -1.587401
> where the precedence of the operators is not what you might expect.  Now that could be considered a bug, since apparently
>
>> -4^(1/2)
> [1] -2
>
> which comes as rather a surprise!
>
> Bill.
>
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Kjetil Halvorsen
> Sent: Wednesday, 27 October 2010 9:17 AM
> To: Gregory Ryslik
> Cc: r-help Help
> Subject: Re: [R] cube root of a negative number
>
> Look at this:
>
>> x<- as.complex(-4)
>> x
> [1] -4+0i
>> x^(1/3)
> [1] 0.793701+1.37473i
>> (-4)^(1/3)
> [1] NaN
>
> It seems that R gives you the principal root, which is complex, and
> not the real root.
>
> Kjetil
>
> On Tue, Oct 26, 2010 at 8:05 PM, Gregory Ryslik<rsaber at comcast.net>  wrote:
>> Hi,
>>
>> This might be me missing something painfully obvious but why does the cube root of the following produce an NaN?
>>
>>> (-4)^(1/3)
>> [1] NaN
>> As we can see:
>>
>>> (-1.587401)^3
>> [1] -4
>>
>> Thanks!
>>
>> Greg
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>



More information about the R-help mailing list