1 ! Copyright (C) 2004, 2008 Slava Pestov.
2 ! Copyright (C) 2008, Doug Coleman.
3 ! See http://factorcode.org/license.txt for BSD license.
4 USING: kernel kernel.private sequences
5 sequences.private math math.private combinators ;
6 IN: math.integers.private
9 M: integer denominator drop 1 ;
12 M: fixnum >bignum fixnum>bignum ;
15 M: fixnum hashcode* nip ;
16 M: fixnum equal? over bignum? [ >bignum bignum= ] [ 2drop f ] if ;
17 M: fixnum number= eq? ;
20 M: fixnum <= fixnum<= ;
22 M: fixnum >= fixnum>= ;
27 M: fixnum /i fixnum/i ;
28 M: fixnum /f [ >float ] dip >float float/f ;
30 M: fixnum mod fixnum-mod ;
32 M: fixnum /mod fixnum/mod ;
34 M: fixnum bitand fixnum-bitand ;
35 M: fixnum bitor fixnum-bitor ;
36 M: fixnum bitxor fixnum-bitxor ;
37 M: fixnum shift >fixnum fixnum-shift ;
39 M: fixnum bitnot fixnum-bitnot ;
41 M: fixnum bit? neg shift 1 bitand 0 > ;
43 : fixnum-log2 ( x -- n )
44 0 swap [ dup 1 eq? ] [ [ 1+ ] [ 2/ ] bi* ] [ ] until drop ;
46 M: fixnum (log2) fixnum-log2 ;
48 M: bignum >fixnum bignum>fixnum ;
51 M: bignum hashcode* nip >fixnum ;
54 over bignum? [ bignum= ] [
55 swap dup fixnum? [ >bignum bignum= ] [ 2drop f ] if
58 M: bignum number= bignum= ;
61 M: bignum <= bignum<= ;
63 M: bignum >= bignum>= ;
68 M: bignum /i bignum/i ;
69 M: bignum mod bignum-mod ;
71 M: bignum /mod bignum/mod ;
73 M: bignum bitand bignum-bitand ;
74 M: bignum bitor bignum-bitor ;
75 M: bignum bitxor bignum-bitxor ;
76 M: bignum shift >fixnum bignum-shift ;
78 M: bignum bitnot bignum-bitnot ;
79 M: bignum bit? bignum-bit? ;
80 M: bignum (log2) bignum-log2 ;
82 ! Converting ratios to floats. Based on FLOAT-RATIO from
83 ! sbcl/src/code/float.lisp, which has the following license:
85 ! "The software is in the public domain and is
86 ! provided with absolutely no warranty."
88 ! First step: pre-scaling
89 : twos ( x -- y ) dup 1- bitxor log2 ; inline
91 : scale-denonimator ( den -- scaled-den scale' )
92 dup twos neg [ shift ] keep ; inline
94 : pre-scale ( num den -- scale shifted-num scaled-den )
96 tuck [ neg 54 + shift ] [ [ scale-denonimator ] dip + ] 2bi*
100 : shift-mantissa ( scale mantissa -- scale' mantissa' )
101 [ 1+ ] [ 2/ ] bi* ; inline
103 : /f-loop ( scale mantissa den -- scale' fraction-and-guard rem )
104 [ 2dup /i log2 53 > ]
105 [ [ shift-mantissa ] dip ]
106 [ ] while /mod ; inline
108 ! Third step: post-scaling
109 : unscaled-float ( mantissa -- n )
110 52 2^ 1- bitand 1022 52 shift bitor bits>double ; inline
112 : scale-float ( scale mantissa -- float' )
113 [ dup 0 < [ neg 2^ recip ] [ 2^ ] if ] dip * ; inline
115 : post-scale ( scale mantissa -- n )
116 2/ dup log2 52 > [ shift-mantissa ] when
117 unscaled-float scale-float ; inline
120 : /f-abs ( m n -- f )
129 [ zero? [ 1+ ] unless ] [ drop ] if
134 M: bignum /f ( m n -- f )
135 [ [ abs ] bi@ /f-abs ] [ [ 0 < ] bi@ xor ] 2bi [ neg ] when ;