Mercurial > hg > octave-nkf
annotate scripts/general/nthroot.m @ 12121:87237a866c71 release-3-2-x
this branch is no longer maintained and is closed for further development
author | John W. Eaton <jwe@octave.org> |
---|---|
date | Sat, 22 Jan 2011 01:00:54 -0500 |
parents | 1bf0ce0930be |
children |
rev | line source |
---|---|
8920 | 1 ## Copyright (C) 2004, 2006, 2007, 2009 Paul Kienzle |
5827 | 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 ## | |
8494 | 25 ## Compute the n-th root of @var{x}, returning real results for real |
9051
1bf0ce0930be
Grammar check TexInfo in all .m files
Rik <rdrider0-list@yahoo.com>
parents:
8920
diff
changeset
|
26 ## components of @var{x}. For example |
5827 | 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)); |