1 ## Copyright (C) 2004-2012 Paul Kienzle
2 ## Copyright (C) 2010 VZLU Prague
4 ## This file is part of Octave.
6 ## Octave is free software; you can redistribute it and/or modify it
7 ## under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 3 of the License, or (at
9 ## your option) any later version.
11 ## Octave is distributed in the hope that it will be useful, but
12 ## WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ## General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with Octave; see the file COPYING. If not, see
18 ## <http://www.gnu.org/licenses/>.
20 ## Original version by Paul Kienzle distributed as free software in the
24 ## @deftypefn {Function File} {} nthroot (@var{x}, @var{n})
26 ## Compute the n-th root of @var{x}, returning real results for real
27 ## components of @var{x}. For example:
34 ## @result{} 0.50000 - 0.86603i
38 ## @var{x} must have all real entries. @var{n} must be a scalar.
39 ## If @var{n} is an even integer and @var{X} has negative entries, an
41 ## @seealso{realsqrt, sqrt, cbrt}
44 function y = nthroot (x, n)
50 if (any (iscomplex (x(:))))
51 error ("nthroot: X must not contain complex values");
54 if (! isscalar (n) || n == 0)
55 error ("nthroot: N must be a nonzero scalar");
63 y = 1 ./ nthroot (x, -n);
65 ## Compute using power.
66 if (n == fix (n) && mod (n, 2) == 1)
67 y = abs (x) .^ (1/n) .* sign (x);
68 elseif (any (x(:) < 0))
69 error ("nthroot: if X contains negative values, N must be an odd integer");
74 if (finite (n) && n > 0 && n == fix (n))
76 y = ((n-1)*y + x ./ (y.^(n-1))) / n;
77 y = merge (finite (y), y, x);
84 %!assert (nthroot(-32,5), -2);
85 %!assert (nthroot(81,4), 3);
86 %!assert (nthroot(Inf,4), Inf);
87 %!assert (nthroot(-Inf,7), -Inf);
88 %!assert (nthroot(-Inf,-7), 0);
90 %% Test input validation
93 %!error (nthroot (1,2,3))
94 %!error (nthroot (1+j,2))
95 %!error (nthroot (1,[1 2]))
96 %!error (nthroot (1,0))
97 %!error (nthroot (-1,2))