From ad419301af6a1f7ae2aaa888debc507850d4a9a5 Mon Sep 17 00:00:00 2001
From: John Benediktsson <mrjbq7@gmail.com>
Date: Mon, 8 Apr 2013 21:44:35 -0700
Subject: [PATCH] math.factorials: making double-factorial work for negative
 numbers.

---
 extra/math/factorials/factorials-tests.factor | 10 +++++++---
 extra/math/factorials/factorials.factor       | 10 +++++++---
 2 files changed, 14 insertions(+), 6 deletions(-)

diff --git a/extra/math/factorials/factorials-tests.factor b/extra/math/factorials/factorials-tests.factor
index e40b20b9dd..933646cda9 100644
--- a/extra/math/factorials/factorials-tests.factor
+++ b/extra/math/factorials/factorials-tests.factor
@@ -1,4 +1,4 @@
-USING: kernel math.functions sequences tools.test ;
+USING: kernel math.functions math.ranges sequences tools.test ;
 IN: math.factorials
 
 [ 1 ] [ -1 factorial ] unit-test ! not necessarily correct
@@ -6,8 +6,12 @@ IN: math.factorials
 [ 1 ] [ 1 factorial ] unit-test
 [ 3628800 ] [ 10 factorial ] unit-test
 
-{ { 1 1 2 3 8 15 48 105 384 945 } }
-[ 10 iota [ double-factorial ] map ] unit-test
+{
+    {
+        1/0. 1/105 1/0. -1/15 1/0. 1/3 1/0. -1 1/0.
+        1 1 1 2 3 8 15 48 105 384 945 3840
+    }
+} [ -10 10 [a,b] [ double-factorial ] map ] unit-test
 
 { 1 } [ 10 10 factorial/ ] unit-test
 { 720 } [ 10 7 factorial/ ] unit-test
diff --git a/extra/math/factorials/factorials.factor b/extra/math/factorials/factorials.factor
index 8760ce537f..699edd6665 100644
--- a/extra/math/factorials/factorials.factor
+++ b/extra/math/factorials/factorials.factor
@@ -12,9 +12,13 @@ MEMO: factorial ( n -- n! )
 ALIAS: n! factorial
 
 MEMO: double-factorial ( n -- n!! )
-    dup 1 > [
-        dup even? 2 1 ? swap 2 <range> product
-    ] [ drop 1 ] if ;
+    dup [ even? ] [ 0 < ] bi [
+        [ drop 1/0. ] [
+            2 + -1 swap -2 <range> product recip
+        ] if
+    ] [
+        2 3 ? swap 2 <range> product
+    ] if ;
 
 ALIAS: n!! double-factorial