comparison scripts/general/nthroot.m @ 5827:1fe78adb91bc

[project @ 2006-05-22 06:25:14 by jwe]
author jwe
date Mon, 22 May 2006 06:25:14 +0000
parents
children 93c65f2a5668
comparison
equal deleted inserted replaced
5826:6c6ff9b82577 5827:1fe78adb91bc
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
7 ## the Free Software Foundation; either version 2, or (at your option)
8 ## any later version.
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
16 ## along with Octave; see the file COPYING. If not, write to the Free
17 ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18 ## 02110-1301, USA.
19 ##
20 ## Original version by Paul Kienzle distributed as free software in the
21 ## public domain.
22
23 ## -*- texinfo -*-
24 ## @deftypefn {Function File} {} nthroot (@var{x}, @var{n})
25 ##
26 ## Compute the nth root of @var{x}, returning real results for real
27 ## components of @var{x}. For example
28 ##
29 ## @example
30 ## @group
31 ## nthroot (-1, 3)
32 ## @result{} -1
33 ## (-1) ^ (1 / 3)
34 ## @result{} 0.50000 - 0.86603i
35 ## @end group
36 ## @end example
37 ##
38 ## @end deftypefn
39
40 function y = nthroot (x, m)
41
42 if (nargin != 2)
43 print_usage ();
44 endif
45
46 y = x.^(1./m);
47
48 if (isscalar (x))
49 x *= ones (size (m));
50 endif
51
52 if (isscalar (m))
53 m *= ones (size (x));
54 endif
55
56 idx = (mod (m, 2) == 1 & imag (x) == 0 & x < 0);
57
58 if (any (idx(:)))
59 y(idx) = -(-x(idx)).^(1./m(idx));
60 endif
61
62 ## If result is all real, make sure it looks real
63 if (all (imag (y) == 0))
64 y = real (y);
65 endif
66
67 endfunction
68
69 %!assert(nthroot(-1,[3,-3]), [-1,-1],eps);
70 %!assert(nthroot([-1,1],[3.1,-3]), [-1,1].^(1./[3.1,-3]));
71 %!assert(nthroot([-1+1i,-1-1i],3), [-1+1i,-1-1i].^(1/3));