2008-06-28 03:36:20 -04:00
|
|
|
! Copyright (C) 2004, 2008 Slava Pestov.
|
2007-09-20 18:09:08 -04:00
|
|
|
! See http://factorcode.org/license.txt for BSD license.
|
2008-06-28 03:36:20 -04:00
|
|
|
USING: accessors kernel kernel.private math math.functions math.private ;
|
2007-10-14 20:38:23 -04:00
|
|
|
IN: math.ratios
|
|
|
|
|
|
|
|
: >fraction ( a/b -- a b )
|
|
|
|
dup numerator swap denominator ; inline
|
|
|
|
|
|
|
|
: 2>fraction ( a/b c/d -- a c b d )
|
2008-03-29 21:36:58 -04:00
|
|
|
[ >fraction ] bi@ swapd ; inline
|
2007-10-14 20:38:23 -04:00
|
|
|
|
|
|
|
<PRIVATE
|
2007-09-20 18:09:08 -04:00
|
|
|
|
|
|
|
: fraction> ( a b -- a/b )
|
|
|
|
dup 1 number= [ drop ] [ <ratio> ] if ; inline
|
|
|
|
|
2007-10-14 20:38:23 -04:00
|
|
|
: scale ( a/b c/d -- a*d b*c )
|
|
|
|
2>fraction >r * swap r> * swap ; inline
|
|
|
|
|
|
|
|
: ratio+d ( a/b c/d -- b*d )
|
|
|
|
denominator swap denominator * ; inline
|
|
|
|
|
|
|
|
PRIVATE>
|
|
|
|
|
2007-09-20 18:09:08 -04:00
|
|
|
M: integer /
|
|
|
|
dup zero? [
|
2007-10-18 02:38:35 -04:00
|
|
|
"Division by zero" throw
|
2007-09-20 18:09:08 -04:00
|
|
|
] [
|
2008-03-29 21:36:58 -04:00
|
|
|
dup 0 < [ [ neg ] bi@ ] when
|
2007-09-20 18:09:08 -04:00
|
|
|
2dup gcd nip tuck /i >r /i r> fraction>
|
|
|
|
] if ;
|
|
|
|
|
2008-09-02 03:02:05 -04:00
|
|
|
M: ratio hashcode*
|
|
|
|
nip >fraction [ hashcode ] bi@ bitxor ;
|
|
|
|
|
|
|
|
M: ratio equal?
|
|
|
|
over ratio? [
|
|
|
|
2>fraction = [ = ] [ 2drop f ] if
|
|
|
|
] [ 2drop f ] if ;
|
|
|
|
|
2007-09-20 18:09:08 -04:00
|
|
|
M: ratio number=
|
|
|
|
2>fraction number= [ number= ] [ 2drop f ] if ;
|
|
|
|
|
|
|
|
M: ratio >fixnum >fraction /i >fixnum ;
|
|
|
|
M: ratio >bignum >fraction /i >bignum ;
|
|
|
|
M: ratio >float >fraction /f ;
|
|
|
|
|
2008-06-28 03:36:20 -04:00
|
|
|
M: ratio numerator numerator>> ;
|
|
|
|
M: ratio denominator denominator>> ;
|
|
|
|
|
2007-09-20 18:09:08 -04:00
|
|
|
M: ratio < scale < ;
|
|
|
|
M: ratio <= scale <= ;
|
|
|
|
M: ratio > scale > ;
|
|
|
|
M: ratio >= scale >= ;
|
|
|
|
|
|
|
|
M: ratio + 2dup scale + -rot ratio+d / ;
|
|
|
|
M: ratio - 2dup scale - -rot ratio+d / ;
|
|
|
|
M: ratio * 2>fraction * >r * r> / ;
|
|
|
|
M: ratio / scale / ;
|
|
|
|
M: ratio /i scale /i ;
|
2008-04-28 22:26:31 -04:00
|
|
|
M: ratio /f scale /f ;
|
2008-07-22 05:44:44 -04:00
|
|
|
M: ratio mod [ /i ] 2keep rot * - ;
|
2008-02-06 21:05:03 -05:00
|
|
|
M: ratio /mod [ /i ] 2keep mod ;
|