----- Original Message ----- From: "Devon McCormick" <[EMAIL PROTECTED]>
To: "Programming forum" <[email protected]>
Sent: Thursday, February 07, 2008 6:26 PM
Subject: Re: [Jprogramming] Algorithm to represent floating pointnumbersasfractions


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


Yes, I have programmed long ago a GCD routine for C. It uses Euclid's algorithm, but it is limited to integer values. Anyway, from the point of view of efficiency, take into consideration that a GCD routine needs also repeated division or modulus operations.
Best regards.

----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to