changeset 25270:617fe022e965

factor.m: Return output factors of same class as input for Matlab compatibility. * factor.m: Add note to docstring about output being of the same type as input. New variable cls to store class of input variable q. Call feval (cls, pf) to convert pf to original class of input. Add BIST tests.
author Rik <rik@octave.org>
date Mon, 16 Apr 2018 20:43:24 -0700
parents cac96fd5310d
children 49a8d0a2d7ae
files scripts/specfun/factor.m
diffstat 1 files changed, 16 insertions(+), 10 deletions(-) [+]
line wrap: on
line diff
--- a/scripts/specfun/factor.m	Thu Mar 22 23:55:46 2018 -0400
+++ b/scripts/specfun/factor.m	Mon Apr 16 20:43:24 2018 -0700
@@ -23,24 +23,19 @@
 ##
 ## The prime factorization is defined as @code{prod (@var{pf}) == @var{q}}
 ## where every element of @var{pf} is a prime number.  If @code{@var{q} == 1},
-## return 1.
+## return 1.  The output @var{pf} is of the same numeric class as the input.
 ##
 ## With two output arguments, return the unique prime factors @var{pf} and
 ## their multiplicities.  That is,
 ## @code{prod (@var{pf} .^ @var{n}) == @var{q}}.
 ##
-## Implementation Note: The input @var{q} must be less than
-## @code{flintmax} (9.0072e+15) in order to factor correctly.
+## Implementation Note: The input @var{q} must be less than @code{flintmax}
+## (9.0072e+15) in order to factor correctly.
 ## @seealso{gcd, lcm, isprime, primes}
 ## @end deftypefn
 
 ## Author: Paul Kienzle
 
-## 2002-01-28 Paul Kienzle
-## * remove recursion; only check existing primes for multiplicity > 1
-## * return multiplicity as suggested by Dirk Laurie
-## * add error handling
-
 function [pf, n] = factor (q)
 
   if (nargin != 1)
@@ -58,7 +53,8 @@
     return;
   endif
 
-  q = double (q);  # For the time being, calcs rely on double precision var.
+  cls = class (q); # store class
+  q = double (q);  # internal algorithm relies on numbers being doubles.
   qorig = q;
   pf = [];
   ## There is at most one prime greater than sqrt(q), and if it exists,
@@ -79,7 +75,7 @@
   endwhile
   pf = sort (pf);
 
-  ## Verify algorithm was succesful
+  ## Verify algorithm was successful
   q = prod (pf);
   if (q != qorig)
     error ("factor: Q too large to factor");
@@ -94,6 +90,9 @@
     n = diff (idx);
   endif
 
+ ## Restore class of input
+ pf = feval (cls, pf); 
+
 endfunction
 
 
@@ -108,6 +107,13 @@
 %!   assert (all ([0,pf] != [pf,0]));
 %! endfor
 
+%!assert (factor (uint8 (8)), uint8 ([2 2 2]))
+%!assert (factor (single (8)), single ([2 2 2]))
+%!test
+%! [pf, n] = factor (int16 (8));
+%! assert (pf, int16 (2));
+%! assert (n, double (3));
+
 ## Test input validation
 %!error factor ()
 %!error factor (1,2)