[Tutor] converting decimals to fractions

Blake.Garretson@dana.com Blake.Garretson@dana.com
Mon, 8 Oct 2001 13:13:29 -0400


This is less of a Python question than it is an algorithm question, but it
should still apply since Python has some cool data structures available to
apply to the solution.

I have a script that does some length calculations and prints out results
in decimal inches.  (e.g. 1.537", 4.230", etc.)  Converting these to
fractions of an inch is simple enough (e.g. 1+537/1000, 4+23/100, etc.),
but suppose I only want answers in the standard fractions of an inch (i.e.
fourths of and inch, thirty-seconds of an inch, etc.).

I'm looking for suggestions on implementation.  My approach is to use a
lookup table, probably in dictionary form.  The table will contain "bins"
of fractions in increments of 1/32 with upper and lower limits for the
decimal equivlent.  The limits would be calculated by adding and
subtracting 1/64 to the base number.  For instance, a given decimal would
be determined to be 3/32 if the decimal equivalent was between
0.09375+0.015625 and 0.09375-0.015625.

The program could create the lookup table right at the beginning, and the
table would hold all of these upper and lower limits along with their
corresponding fraction.  The fraction itself (in string form) would
probably be the dictionary key.  To convert a decimal, I would just use a
loop to compare the number to each set of limits.

Does anyone have a better method for this?

Thanks,
Blake Garretson