Dear Robert,

Indeed! I’d rather not use Float at all in this project as it’s

financial math and float quirks will cause me problems. I’d be prepared

to take the performance hit and just turn off Float if I could…

you could use a “continued fractions” approximation

http://mathworld.wolfram.com/ContinuedFraction.html

to your Float number and then work with fractions without

any further loss in accuracy. Continued fractions are in a sense the

best possible approximations to irrational numbers

(and of course to rational numbers, the latter being

fractions themselves).

Once you have a fraction (use the code below to get it

from a continued fraction), you can calculate with it in Ruby

using Rational:

require “rational”

a=Rational(1,2)

b=Rational(3,4)

p a+b # => Rational (5,4) , as 5/4 == 1/2+3/4

p (a+b).to_f # => 1.25

Below is some code to give you the continued fraction representation

(4) in the webpage cited above.

From the continued fraction representation, you can obtain the

partial quotients mentioned in (11) of the cited webpage by the method

cont_fract_to_fract below.

Best regards,

Axel

class Float

def cont_fract_appr(*prec)*

a=[self.floor]

t=[self-self.floor]

res=[]

if prec==[]

prec=10*-8

else

prec=prec[0]

end

k=1

rem=t[-1]

while rem.abs>prec

r_new=1/t[-1]

if (r_new+prec).floor>r_new.floor

r_new=r_new+prec

end

a[k]=r_new.floor

t[k]=r_new-r_new.floor

k=k+1

p,q=(a.cont_fract_to_fract)

rem=(self-p[-1].to_f/q[-1].to_f).abs

end

return a

end

end

class Array

def cont_fract_to_fract

# produce the partial fractions (see eq. 11 of webpage)

p=[0,1]

q=[1,0]

for n in 2…self.length+1

p<<self[n-2]*p[-1]+p[-2]

q<<self[n-2]*q[-1]+q[-2]

end

return p,q

end

end

# usage example:

f=Math::PI

r=f.cont_fract_appr

p ‘the continued fraction approximation (to precision 10**-8 is)’

p r