Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |
 User Name: Password: Remember me

New Free Tools on Dev Shed!
We're Excited to announce that Dev Shed now has 70 free tools on the site. To learn more, click here!

 Dev Shed Forums Sponsor:
#16
March 25th, 2004, 01:02 PM
 Strike
Contributing User

Join Date: Dec 2001
Location: Houston, TX
Posts: 383
Time spent in forums: 1 h 41 m 27 sec
Reputation Power: 12
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.
__________________
Debian - because life's too short for worrying.
Best. (Python.) IRC bot. ever.

#17
March 25th, 2004, 03:25 PM
 Grim Archon
Mini me.

Join Date: Nov 2003
Location: Cambridge, UK
Posts: 783
Time spent in forums: 3 Days 2 h 15 m 57 sec
Reputation Power: 13
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"%(value-integer)
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 (rem-float(dec[index-1])) < (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))
__________________
*** Experimental Python Markup CGI V2 ***

#18
March 25th, 2004, 05:12 PM
 DFarist
Registered User

Join Date: Jul 2003
Posts: 16
Time spent in forums: 1 m 52 sec
Reputation Power: 0
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

#19
March 25th, 2004, 06:10 PM
 DFarist
Registered User

Join Date: Jul 2003
Posts: 16
Time spent in forums: 1 m 52 sec
Reputation Power: 0
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.

#20
March 25th, 2004, 06:54 PM
 Grim Archon
Mini me.

Join Date: Nov 2003
Location: Cambridge, UK
Posts: 783
Time spent in forums: 3 Days 2 h 15 m 57 sec
Reputation Power: 13
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 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.

Grim

#21
March 30th, 2004, 12:35 AM
 TheBlackMamba
Registered User

Join Date: Apr 2003
Posts: 25
Time spent in forums: < 1 sec
Reputation Power: 0
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.

 Viewing: Dev Shed Forums > Programming Languages > Python Programming > Mixed numbers and decimals?!?

## Developer Shed Advertisers and Affiliates

 Thread Tools Search this Thread Search this Thread: Advanced Search Display Modes Rate This Thread Linear Mode Rate This Thread: 5 : Excellent 4 : Good 3 : Average 2 : Bad 1 : Terrible

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts vB code is On Smilies are On [IMG] code is On HTML code is Off
 View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox Forum Jump Please select one User Control Panel Private Messages Subscriptions Who's Online Search Forums Forums Home -------------------- Programming Languages    PHP Development        PHP FAQs and Stickies    Perl Programming        Perl FAQs and Stickies    C Programming        C Programming FAQs and Stickies    Java Help        Java FAQs    Python Programming        Python Programming FAQs    Ruby Programming        Ruby Programming FAQs    Game Development        Game Development FAQs Programming Languages - More    ASP Programming        ASP Programming FAQs    .Net Development        .Net Development FAQs    Visual Basic Programming        Visual Basic Programming FAQs    Software Design        Software Design FAQs    ColdFusion Development        ColdFusion Development FAQs    Delphi Programming        Delphi Programming FAQs    Regex Programming        Regex Programming FAQs    XML Programming        XML Programming FAQs    Other Programming Languages        Other Programming Languages FAQs Web Design    HTML Programming        HTML Programming FAQs    JavaScript Development        JavaScript Development FAQs    CSS Help        CSS Help FAQs    Flash Help        Flash Help FAQs    Photoshop Help        Photoshop Help FAQs    Web Design Help        Web Design Help FAQs    Website Critiques        Website Critiques FAQs    Search Engine Optimization        Search Engine Optimization FAQs Mobile Programming    Mobile Programming        Mobile Programming FAQs    iPhone SDK Development        iPhone SDK Development FAQs    Android Development        Android Development FAQs    BlackBerry Development        BlackBerry Development FAQs Web Site Management    Business Help        Business Help FAQs    Development Software        Development Software FAQs    Scripts        Scripts FAQs Databases    Database Management        Database Management FAQs    DB2 Development        DB2 Development FAQs    MySQL Help        MySQL Help FAQs    PostgreSQL Help        PostgreSQL Help FAQs    Firebird SQL Development        Firebird SQL Development FAQs    MS SQL Development        MS SQL Development FAQs    Oracle Development        Oracle Development FAQs    LDAP Programming        LDAP Programming FAQs System Administration    Mail Server Help        Mail Server Help FAQs    Apache Development        Apache Development FAQs    Security and Cryptography        Security and Cryptography FAQs    Antivirus Protection        Antivirus Protection FAQs    DNS        DNS FAQs    IIS        IIS FAQs    Networking Help        Networking Help FAQs    FTP Help        FTP Help FAQs Operating Systems    BSD Help        BSD Help FAQs    Linux Help        Linux Help FAQs    UNIX Help        UNIX Help FAQs    Windows Help        Windows Help FAQs    Mac Help        Mac Help FAQs Web Hosting    Web Hosting        Web Hosting FAQs    Free Web Hosting        Free Web Hosting FAQs    Web Hosting Requests        Web Hosting Requests FAQs    Web Hosting Offers        Web Hosting Offers FAQs Computer Hardware    Computer Hardware    CPUs        CPUs FAQs    Cooling        Cooling FAQs    Embedded Programming        Embedded Programming FAQs    Motherboards        Motherboards FAQs    Multimedia Hardware        Multimedia Hardware FAQs Other    Dev Shed Lounge        Dev Shed Lounge FAQs    Development Articles        Development Articles FAQs    Beginner Programming        Beginner Programming FAQs    Hire A Programmer        Hire A Programmer FAQs    Project Help Wanted        Project Help Wanted FAQs Latest News Updated Hourly    Technology News    Business News    Science News Forum Information    Forum Rules/Guidelines        Forum Rules/Guidelines FAQs    Forum Announcements        Forum Announcements FAQs    Dev Shed Gaming Center        Go to the Dev Shed Battle Arena        Go to the Dev Shed Arcade Games        Go to the Legend of the Green Dragon    Suggestions & Feedback        Suggestions & Feedback FAQs

 Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |