5827
|
1 ## Copyright (C) 2004 Paul Kienzle |
|
2 ## |
|
3 ## This file is part of Octave. |
|
4 ## |
|
5 ## Octave is free software; you can redistribute it and/or modify it |
|
6 ## under the terms of the GNU General Public License as published by |
7016
|
7 ## the Free Software Foundation; either version 3 of the License, or (at |
|
8 ## your option) any later version. |
5827
|
9 ## |
|
10 ## Octave is distributed in the hope that it will be useful, but |
|
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
13 ## General Public License for more details. |
|
14 ## |
|
15 ## You should have received a copy of the GNU General Public License |
7016
|
16 ## along with Octave; see the file COPYING. If not, see |
|
17 ## <http://www.gnu.org/licenses/>. |
5827
|
18 ## |
|
19 ## Original version by Paul Kienzle distributed as free software in the |
|
20 ## public domain. |
|
21 |
|
22 ## -*- texinfo -*- |
|
23 ## @deftypefn {Function File} {} nthroot (@var{x}, @var{n}) |
|
24 ## |
|
25 ## Compute the nth root of @var{x}, returning real results for real |
|
26 ## components of @var{x}. For example |
|
27 ## |
|
28 ## @example |
|
29 ## @group |
|
30 ## nthroot (-1, 3) |
|
31 ## @result{} -1 |
|
32 ## (-1) ^ (1 / 3) |
|
33 ## @result{} 0.50000 - 0.86603i |
|
34 ## @end group |
|
35 ## @end example |
|
36 ## |
|
37 ## @end deftypefn |
|
38 |
|
39 function y = nthroot (x, m) |
|
40 |
|
41 if (nargin != 2) |
|
42 print_usage (); |
|
43 endif |
|
44 |
|
45 y = x.^(1./m); |
|
46 |
|
47 if (isscalar (x)) |
|
48 x *= ones (size (m)); |
|
49 endif |
|
50 |
|
51 if (isscalar (m)) |
|
52 m *= ones (size (x)); |
|
53 endif |
|
54 |
|
55 idx = (mod (m, 2) == 1 & imag (x) == 0 & x < 0); |
|
56 |
|
57 if (any (idx(:))) |
|
58 y(idx) = -(-x(idx)).^(1./m(idx)); |
|
59 endif |
|
60 |
|
61 ## If result is all real, make sure it looks real |
|
62 if (all (imag (y) == 0)) |
|
63 y = real (y); |
|
64 endif |
|
65 |
|
66 endfunction |
|
67 |
|
68 %!assert(nthroot(-1,[3,-3]), [-1,-1],eps); |
|
69 %!assert(nthroot([-1,1],[3.1,-3]), [-1,1].^(1./[3.1,-3])); |
|
70 %!assert(nthroot([-1+1i,-1-1i],3), [-1+1i,-1-1i].^(1/3)); |