# [R] nth root

Stavros Macrakis macrakis at alum.mit.edu
Thu Mar 19 20:42:59 CET 2009

```Matlab's Nthroot calculates the real nth root.  For positive a, you
can use a^(1/b); for negative a, b must be odd for the result to be
real, and you can use -abs(a)^(1/b).  So you could write:

nthroot <- function(a,b) ifelse( b %% 2 == 1 | a >= 0,
sign(a)*abs(a)^(1/b), NaN)

This is a so-called Vectorized function, i.e. f(A,B) == c(
f(A,B), f(A,B), ...) for vectors A, B of equal length.

This does *not* handle the case where b is the inverse of an integer
(e.g. nthroot(-1,1/3) ==? (-1)^3), since in general you cannot count
on 1/(1/int) being an integer.

If on the other hand you want the complex principal value of the nth
root, you can use (a+0i)^(1/b).

-s

On Thu, Mar 19, 2009 at 11:21 AM, Martin Biuw <martin.biuw at npolar.no> wrote:
> Hi,
> Is there a function in R to calculate the nth root, similar to the
> MATLAB function NTHROOT()?
> Thanks,
> Martin Biuw
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help