# Re: [R] R: to the power

Date: Wed 13 Jul 2005 - 00:16:55 EST

In general, x^y is evaluated as exp(y*log(x)). In your case, x is negative, so log(x) is NaN. Note also that 1/3 is not represented exactly in your computer anyway, so you would not get an exact cube root this way; e.g.:

R> format((1234567891112^3)^(1/3),digits=16) [1] "1234567891112.001"

(Probably a bad example, but you get the idea.)

In general, sign(x)*(abs(x)^(1/3)) is the way to go for cube roots.

David L. Reiner

> -----Original Message-----
> From: r-help-bounces@stat.math.ethz.ch [mailto:r-help-
> bounces@stat.math.ethz.ch] On Behalf Of
> allan_sta_staff_sci_main_uct@mail.uct.ac.za
> Sent: Tuesday, July 12, 2005 8:54 AM
> To: Duncan Murdoch
> Cc: r-help@stat.math.ethz.ch
> Subject: Re: [R] R: to the power
>
> hi all
>
> i simply wanted to work with real numbers and thought that (-8)^(1/3)
> should
> work.
>
> sorry for not making the question clearer.
>
> /
> allan
>
> Quoting Duncan Murdoch <murdoch@stats.uwo.ca>:
>
> > On 7/12/2005 9:29 AM, Robin Hankin wrote:
> > > Hi
> > >
> > > I find that one often needs to keep reals real and complexes
complex.
> > >
> > > Try this:
> > >
> > > "cuberooti" <-
> > > function (x)
> > > {
> > > if (is.complex(x)) {
> > > return(sqrt(x + (0+0i)))
> > > }
> > > sign(x)* abs(x)^(1/3)
> > > }
> > >
> > >
> > > best wishes
> > >
> > > [see that (0+0i) sitting there!]
> >
> > I don't understand this.
> >
> > 1. I don't think you meant to use sqrt() there, did you??
> >
> > 2. What effect does the 0+0i have? x has already been determined
to be
> > complex.
> >
> > Duncan Murdoch
> >
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help