]> gitweb.factorcode.org Git - factor.git/commitdiff
math: faster recip for integers and ratios.
authorJohn Benediktsson <mrjbq7@gmail.com>
Sun, 2 Sep 2012 16:47:31 +0000 (09:47 -0700)
committerJohn Benediktsson <mrjbq7@gmail.com>
Sun, 2 Sep 2012 16:47:31 +0000 (09:47 -0700)
basis/math/ratios/ratios.factor
core/math/math.factor

index 1f95732a1862032fe01f5328be7bb3f03bf87cbb..bf572ac352f523f6909e23ab4a0cff972c7beb9d 100644 (file)
@@ -33,6 +33,16 @@ M: integer /
         2dup fast-gcd [ /i ] curry bi@ fraction>
     ] if-zero ;
 
+M: integer recip
+    1 swap [
+        division-by-zero
+    ] [
+        dup 0 < [ [ neg ] bi@ ] when fraction>
+    ] if-zero ;
+
+M: ratio recip
+    >fraction swap fraction> ;
+
 M: ratio hashcode*
     nip >fraction [ hashcode ] bi@ bitxor ;
 
index b86cc9565ce33e80a50e8f1cc6a0f73562cac1e3..20593bd48a89e1db518b1e3acf91e687f84adc9c 100644 (file)
@@ -69,7 +69,6 @@ ERROR: log2-expects-positive x ;
 : 2/ ( x -- y ) -1 shift ; inline
 : sq ( x -- y ) dup * ; inline
 : neg ( x -- -x ) -1 * ; inline
-: recip ( x -- y ) 1 swap / ; inline
 : sgn ( x -- n ) dup 0 < [ drop -1 ] [ 0 > 1 0 ? ] if ; inline
 : ?1+ ( x -- y ) [ 1 + ] [ 0 ] if* ; inline
 : rem ( x y -- z ) abs [ mod ] [ + ] [ mod ] tri ; foldable
@@ -100,6 +99,10 @@ TUPLE: complex { real real read-only } { imaginary real read-only } ;
 
 UNION: number real complex ;
 
+GENERIC: recip ( x -- y )
+
+M: number recip 1 swap / ; inline
+
 : fp-bitwise= ( x y -- ? ) [ double>bits ] same? ; inline
 
 GENERIC: fp-special? ( x -- ? )