On Tue, 2 Jan 2007, Terry Carroll wrote:

> Dick, if your goal is to have a routine to get the fraction with the least 
> possible error (as opposed to learing how to use Decimal), have a look at 
> this recipe from the Python Cookbook:
> 
>  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52317

BTW, to get the higher precision in Decimal:

import decimal

def farey(v, lim):
  '''Named after James Farey, an English surveyor.
  No error checking on args -- lim = max denominator,
  results are (numerator, denominator), (1,0) is infinity
  '''
  if v < 0:
    n,d = farey(-v, lim)
    return int(-n),int(d)
  z = lim-lim   # get 0 of right type for denominator
  lower, upper = (z,z+1), (z+1,z)
  while 1:
    mediant = (lower[0] + upper[0]), (lower[1]+upper[1])
    if v * mediant[1] > mediant[0]:
        if lim < mediant[1]: return (int(upper[0]), int(upper[1]))
        lower = mediant
    elif v * mediant[1] == mediant[0]:
        if lim >= mediant[1]: return (int(mediant[0]), int(mediant[1]))
        if lower[1] < upper[1]: return (int(lower[0]), int(lower[1]))
        return (int(upper[0]), int(upper[1]))
    else:
        if lim < mediant[1]: return lower
        upper = mediant

dec = decimal.Decimal("0.345765988765560057657654654")
me = decimal.Decimal("0.0000000001")
max_denom = 1/me

(num, denom) = farey(dec,max_denom)
error = abs(decimal.Decimal(str(float(num)/denom)) - dec) *100
print "%s = %d/%d with %s per cent error" % (dec, num, denom, error)


Which gives:

0.345765988765560057657654654 = 878844001/2541730620 with 
4.3994234234534600E-11 per cent error

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to