March 25th, 2004, 12:02 PM

Never expect to get the exact number out of floating point math, because a lot of the time you won't (and simply can't, with the standard datatypes). If you store 1/3 into a variable (that is, the value Python calculates 1/3 to be), you can't get 1/3 back. You'll only get an approximation.
Read this for more detail.
March 25th, 2004, 02:25 PM

This is a tidied up 'practical' version. It provides a fractional answer to the nearest smallest fraction (in this case 1/32nd)
Code:
from __future__ import division
import re
imperial = re.compile(r"(\d+\s+\d+/\d+)(\d+/\d+)")
metric = re.compile(r"(\d*\.\d+)(\d+)(?!.*/)")
fractions = {}
fractions['0.00000'] = ''
for frac in [32, 16, 10, 8, 5, 4, 3, 2]:
for n in range(1, frac):
fractions["%0.5f"%(n/float(frac))] = "%s/%s"%(n, frac)
dec = fractions.keys()
dec.sort()
def NumericInput(prompt="Input value:"):
while True:
inp = raw_input(prompt).strip()
matchi = imperial.match(inp)
matchm = metric.match(inp)
if matchi:
val = matchi.group().replace(" ", "+", 1)
elif matchm:
val = matchm.group()
else:
print "Input format '1' , '1.5' or '1 1/2', retry..."
continue
value = eval(val)
return value
def ImpPrint(value):
integer = int(value)
remainder = "%0.5f"%(valueinteger)
if fractions.has_key(remainder):
return "%d %s"%(integer, fractions[remainder])
else:
rem = float(remainder)
for index, value in enumerate(dec):
if rem < float(value):
break
if (remfloat(dec[index1])) < (float(dec[index])rem):
index = 1
return "%d %s"%(integer, fractions[dec[index]])
q = NumericInput(" Number of doors: ")
w = NumericInput(" Width: ")
l = NumericInput(" Length: ")
c = NumericInput(" Cut depth: ")
m = NumericInput("Machine clearance: ")
s = NumericInput(" Stile width: ")
r = NumericInput(" Rail width: ")
sl = l
rl = w(2*s)+(2*c)
pl = sl(2*r)(2*c)(2*m)
pw = w(2*s)(2*c)(2*m)
rq = 2*q
sq = 2*q
pq = q
print "Cutlist for: %4d doors [%8sx%8s]"%(q, ImpPrint(w), ImpPrint(l))
print ""
print " Panels: %4d [%8sx%8s]"%(pq, ImpPrint(pw), ImpPrint(pl))
print " Stiles: %4d [%8sx%8s]"%(sq, ImpPrint(s), ImpPrint(sl))
print " Rails: %4d [%8sx%8s]"%(rq, ImpPrint(r), ImpPrint(rl))
March 25th, 2004, 04:12 PM

Okay, yeah, I guess using the floats didnt work quiet like I wanted. Out of all the fractions I tried they worked. But 1/3 must be an anamoly.
Yes Grim you are right. Credit were credit is do. I meant to mention that link but I was so excited I forgot to. So thank you. Although I did have to write my own code to get the decimal into the fraction. So some of it was original. I only used the reduction formula.
Ummm.... I like your code Grim, but I dont know exactly what is going on. Remember I am a novice. I would like to be able to print the output a little easier.
I also had the intention of put the loops in the program, but this was just the basic code I was working on, but thanks for you comments. If I would have overlooked that it would have been bad.
Thanks for your replies.
I will work on it more and try to fix the 1/3 error.
DFarist
March 25th, 2004, 05:10 PM

Thank you everybody. I have finally figured out exactly what I wanted. Grim, thank you for your help, I was able to work out what was going on in your code and modify it to fit my needs. I was also able to figure out the 1/3 error and solved it, but Grims code is shorter. I have learned quiet a bit from this experience so again. Thank you all.
I will post the final code when I am finished modifying it.
March 25th, 2004, 05:54 PM

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'.
Code:
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 forloop 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 forloop.
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.
Grim
March 29th, 2004, 11:35 PM

On a related note, I was reading the PEPs for py 2.4 and it mentioned the adition of a decimal type with a defined limit of precision. Also, there's another PEP for adding rationals (fractions) that sounds interesting.
There's never a dull moment with the snake.