Message-ID: <8b356f880903191242i1a300b61yd3b2ac9c8fb77cd0@mail.gmail.com>
Date: 2009-03-19T19:42:59Z
From: Stavros Macrakis
Subject: nth root
In-Reply-To: <5A9DE79F4DF0EA4BA86478B0D88DA44E5CAA01@louise.nett.npolar>
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[1],B[1]), f(A[2],B[2]), ...) 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
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>