1 ## Copyright (C) 1994-2012 John W. Eaton
3 ## This file is part of Octave.
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 3 of the License, or (at
8 ## your option) any later version.
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.
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING. If not, see
17 ## <http://www.gnu.org/licenses/>.
20 ## @deftypefn {Function File} {} roots (@var{v})
22 ## For a vector @var{v} with @math{N} components, return
23 ## the roots of the polynomial
26 ## v_1 z^{N-1} + \cdots + v_{N-1} z + v_N.
32 ## v(1) * z^(N-1) + @dots{} + v(N-1) * z + v(N)
37 ## As an example, the following code finds the roots of the quadratic
40 ## $$ p(x) = x^2 - 5. $$
59 ## Note that the true result is
73 ## @seealso{poly, compan, fzero}
76 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
77 ## Created: 24 December 1993
80 function r = roots (v)
82 if (nargin != 1 || min (size (v)) > 1)
84 elseif (any (isnan(v) | isinf(v)))
85 error ("roots: inputs must not contain Inf or NaN");
91 ## If v = [ 0 ... 0 v(k+1) ... v(k+l) 0 ... 0 ], we can remove the
92 ## leading k zeros and n - k - l roots of the polynomial are zero.
97 f = find (v ./ max (abs (v)));
105 A = diag (ones (1, l-2), -1);
106 A(1,:) = -v(2:l) ./ v(1);
109 tmp = zeros (n - f(m), 1);
113 r = zeros (n - f(m), 1);
122 %! p = [poly([3 3 3 3]), 0 0 0 0];
123 %! r = sort (roots (p));
124 %! assert (r, [0; 0; 0; 0; 3; 3; 3; 3], 0.001)
126 %!assert(all (all (abs (roots ([1, -6, 11, -6]) - [3; 2; 1]) < sqrt (eps))));
128 %!assert(isempty (roots ([])));
130 %!error roots ([1, 2; 3, 4]);
132 %!assert(isempty (roots (1)));
134 %!error roots ([1, 2; 3, 4]);
136 %!error roots ([1 Inf 1]);
138 %!error roots ([1 NaN 1]);
140 %!assert(roots ([1e-200, -1e200, 1]), 1e-200)
141 %!assert(roots ([1e-200, -1e200 * 1i, 1]), -1e-200 * 1i)