Conditionally set max_recursion_depth in nchoosek

Francesco Potortì Potorti at isti.cnr.it
Tue Nov 25 08:35:21 CST 2008


The nchoosek function may be called with n greater than the default
maximum recursion depth.  I recently happened to call nchoosek(1:430,2).

In this case, nchoosek gives many errors (I suspect 430-256 of them).
The cleanest fix would be to rewrite nchoosek to work non-recursively,
but I do not know how to do that.  So I propose the following patch.

# HG changeset patch
# User Francesco Potortì <pot at gnu.org>
# Date 1227622909 -3600
# Node ID aed592b1eda936b05eb977135ec8c9bae10a11c0
# Parent  bf8314b68e463dcb8d2bc173a02f5b7f257487b3
Conditionally set max_recursion_depth in nchoosek

diff -r bf8314b68e46 -r aed592b1eda9 scripts/ChangeLog
--- a/scripts/ChangeLog	Wed Oct 15 13:52:49 2008 +0200
+++ b/scripts/ChangeLog	Tue Nov 25 15:21:49 2008 +0100
@@ -1,3 +1,7 @@ 2008-10-14  Francesco Potortì  <pot at gnu.
+2008-11-25  Francesco Potortì  <pot at gnu.org>
+
+	* specfun/nchoosek.m: Conditionally set max_recursion_depth.
+
 2008-10-14  Francesco Potortì  <pot at gnu.org>
 
 	* general/prepad.m: Add reference to postpad.
diff -r bf8314b68e46 -r aed592b1eda9 scripts/specfun/nchoosek.m
--- a/scripts/specfun/nchoosek.m	Wed Oct 15 13:52:49 2008 +0200
+++ b/scripts/specfun/nchoosek.m	Tue Nov 25 15:21:49 2008 +0100
@@ -75,9 +75,21 @@ function A = nchoosek (v, k)
   elseif (k == n)
      A = v(:).';
   else
-    m = round (exp (sum (log (k:n-1)) - sum (log (2:n-k))));
-    A = [v(1)*ones(m,1), nchoosek(v(2:n),k-1);
-	 nchoosek(v(2:n),k)];
+    oldmax = max_recursion_depth ();
+    unwind_protect
+      if (n > oldmax)
+	max_recursion_depth (n);
+      else
+	oldmax = false;
+      endif
+      m = round (exp (sum (log (k:n-1)) - sum (log (2:n-k))));
+      A = [v(1)*ones(m,1), nchoosek(v(2:n),k-1);
+	   nchoosek(v(2:n),k)];
+    unwind_protect_cleanup
+      if (oldmax)
+	max_recursion_depth (oldmax);
+      endif
+    end_unwind_protect
   endif
 
 endfunction

-- 
Francesco Potortì (ricercatore)        Voice: +39 050 315 3058 (op.2111)
ISTI - Area della ricerca CNR          Fax:   +39 050 315 2040
via G. Moruzzi 1, I-56124 Pisa         Email: Potorti at isti.cnr.it
(entrance 20, 1st floor, room C71)     Web:   http://fly.isti.cnr.it/


More information about the Octave-maintainers mailing list