[Tutor] converting decimals to fractions
Kirby Urner
urnerk@qwest.net
Mon, 08 Oct 2001 12:13:34 -0700
Probably easier to calculate on the fly, vs. do a
lookup table.
One algorithm is: take the decimal part of n and
convert it to the nearest x/32. Then reduce x/32 to
lowest terms by dividing x, 32 by their gcd (greatest
common divisor).
def div32(n):
"x for closest x/32"
return round((n-int(n))*1000/32.)
def gcd(a,b):
"Euclidean Algorithm (recursive form)"
if b==0: return a
else: return gcd(b,a%b)
def mkinch(n):
numer = div32(n)
thegcd = gcd(numer,32)
return "%s %s/%s" % \
(int(n),int(numer/thegcd),int(32/thegcd))
>>> mkinch(1.133)
'1 1/8'
>>> mkinch(1.185)
'1 3/16'
>>> mkinch(1.1)
'1 3/32'
Since writing this, I've seen Tim's. His is no doubt
faster, as it takes advantage of the base 2 aspect of
your problem thru bit shifting.
Kirby