[Tutor] Need help with rewriting script to use Decimal module
Terry Carroll
carroll at tjc.com
Tue Jan 2 22:17:17 CET 2007
On Mon, 1 Jan 2007, Dick Moores wrote:
> bestFracForMinimumError() is only a small part of a program I wrote
> long ago, called frac.py
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
> dec = .345765988765560057657654654
> me = .0000000001
> num, denom, error = bestFracForMinimumError(dec, me)
> print "%f = %d/%d with %f per cent error" % (dec, num, denom, error)
The parameters are different from yours, but as I understand it, your
equivalent is:
>>> dec = .345765988765560057657654654
>>> me = .0000000001
>>> max_denom = 1/me
>>> (num, denom) = farey(dec,max_denom)
>>> error = abs((num/denom) - dec) *100
>>> print "%f = %d/%d with %f per cent error" % (dec, num, denom, error)
0.345766 = 40258524/116432863 with 0.000000 per cent error
>>>
More information about the Tutor
mailing list