Just a quick explanation then
I build up a dictionary called fractions
, the keys to the dictionary are string representation of the floating point values to 5 decimal places. The content of each entry is the fraction as a string. e.g fractions
['0.50000'] contains '1/2' and fractions['0.33333'] contains '1/3'.
for frac in [32, 16, 10, 8, 5, 4, 3, 2]: #iterate over the list of denominators
for n in range(1, frac):
fractions["%0.5f"%(n/float(frac))] = "%s/%s"%(n, frac)
From the code above you should see that frac
starts with 32 and the inner for-loop is done 32 times to create 32 fractions
dictionary entries. Then frac
becomes 16, this time every other fractions
entry is replaced with an n/16 fraction. This is repeated for each of the numbers in the list. Basically this creates a dictionary of all 'legal' fractions. You add or take from the dictionary by modifying the list of denominators in the outer for-loop.
The function NumericInput is much the same as yours the code is in a while loop. This while loop keeps repeating the error message and then asks for input until one of the correct formats is entered.
The ImpPrint function makes use of our fractions
dictionary. Firstly the number is split in to integer and remainder. The remainder is converted to a string and formated to 5 decimal places. With this value we test the fractions
dictionary for a key match with fractions.has_key(remainder)
, If there is a match we return the fraction string fractions[remainder]
. If there is no match then the the next step is to find the closest match. We do this by simple stepping through the list of values dec
I created earlier. We interate over the list until we find one that is bigger than our remainder. We then break out of the iterating for loop.
What we now do is subtract the remainder from the index to find the difference. We do that also with the remainder and the previous index. Which ever index gives us the smallest difference is the closest match to our remainder. That gives us the farction to print.
As the smallest fraction I define is 1/32 then the largest difference between an index and remainder will only be 1/64.
You can keep adding to the denominator list to increase the resolution.