Interestingly, the English entry for this (continued fractions) on Wikipedia
(http://en.wikipedia.org/wiki/Continued_fractions) mentions "The denominator
is usually a power of two on modern computers, and a power of ten on
electronic calculators, so a variant of Euclid's GCD algorithm can be used
to give exact results."  (referring to
http://en.wikipedia.org/wiki/Euclidean_algorithm)

This ties in with Roger's use of GCD in his solution.  The explicit
algorithm these pages give for computing continued
fractions looks potentially expensive as it relies on repeated inversion.  I
would think Roger's J version would be simpler to code in C if you have a
GCD routine already.

Playing around with continued fractions, I noticed a few interesting things.
 First of all, I defined

   contfrac=: 13 : '(+`%)/1,44$y'"1   NB. Arbitrary 44 as this seems to give
about 16 digits precision

but it displays as

([: (+`%`:3) 1 , 44 $ ])"1

Why is my "/" replaced by "`:3"?  It seems to work as expected.

Anyway, trying this for a few sets of values revealed that very simple
inputs give interesting results:

   contfrac 1 1
1.618034           NB. Phi (the golden ratio)
   contfrac 1 2
1.4142136         NB. %:2
   contfrac 2 2
1.7320508         NB. %:3


On 2/7/08, Ricardo Forno <[EMAIL PROTECTED]> wrote:
>
>
> ----- Original Message -----
> From: "Roger Hui" <[EMAIL PROTECTED]>
> To: "Programming forum" <[email protected]>
> Sent: Thursday, February 07, 2008 3:11 PM
> Subject: Re: [Jprogramming] Algorithm to represent floating point
> numbersasfractions
>
>
> > pq=: 3 : 0
> > q=. <. 0.5 + % 1 +. y
> > p=. <. 0.5 + y * q
> > p,q
> > )
> >
> >   pq 0.625
> > 5 8
> >   pq 0.07
> > 7 100
> >
> >   ] y=: ? 0
> > 0.536676
> >   pq y
> > 9.08637e12 1.69308e13
> >   %/ pq y
> > 0.536676
> >   y - %/ pq y
> > _4.51861e_14
> >
> > Note that +. (GCD) is tolerant.  Depending on your needs you
> > may want to use +.!.0 (0 tolerance) instead of +. .
>
> I found the detailed algorithm here (Spanish explanation). Anyway, it is
> not
> difficult at all, and it adapts better to C programming:
> http://enciclopedia.us.es/index.php/Fracci%C3%B3n_continua
>
> Thanks a lot.
>
> ----------------------------------------------------------------------
> For information about J forums see http://www.jsoftware.com/forums.htm
>



-- 
Devon McCormick, CFA
^me^ at acm.
org is my
preferred e-mail
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to