Skip to content
Prev 174261 / 398506 Next

nth root

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: