factor/extra/math/continued-fractions/continued-fractions.factor

27 lines
641 B
Factor
Raw Normal View History

2009-03-02 13:10:43 -05:00
! Copyright (C) 2009 Samuel Tardieu.
! See http://factorcode.org/license.txt for BSD license.
USING: kernel math math.functions sequences vectors ;
IN: math.continued-fractions
<PRIVATE
2012-07-16 18:45:21 -04:00
: split-float ( f -- d i )
dup >integer [ - ] keep ;
2009-03-02 13:10:43 -05:00
2012-07-16 18:45:21 -04:00
: closest ( seq -- newseq )
unclip-last round >integer suffix ;
2009-03-02 13:10:43 -05:00
PRIVATE>
: next-approx ( seq -- )
dup [ pop split-float ] [ push ] bi
2012-07-16 18:45:21 -04:00
[ drop ] [ recip swap push ] if-zero ;
2009-03-02 13:10:43 -05:00
: >ratio ( seq -- a/b )
2012-07-16 18:45:21 -04:00
closest reverse! unclip-slice [ swap recip + ] reduce ;
2009-03-02 13:10:43 -05:00
: approx ( epsilon float -- a/b )
dup 1vector
[ 3dup >ratio - abs < ] [ dup next-approx ] while
2nip >ratio ;