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

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #16  
Old March 25th, 2004, 12:02 PM
Strike Strike is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2001
Location: Houston, TX
Posts: 383 Strike User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 41 m 27 sec
Reputation Power: 12
Send a message via ICQ to Strike Send a message via AIM to Strike Send a message via Yahoo to Strike
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.

Reply With Quote
  #17  
Old March 25th, 2004, 02:25 PM
Grim Archon's Avatar
Grim Archon Grim Archon is offline
Mini me.
Dev Shed Novice (500 - 999 posts)
 
Join Date: Nov 2003
Location: Cambridge, UK
Posts: 783 Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)  Folding Points: 1488 Folding Title: Novice Folder
Time spent in forums: 3 Days 2 h 15 m 57 sec
Reputation Power: 12
Send a message via MSN to Grim Archon
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 ***

Reply With Quote
  #18  
Old March 25th, 2004, 04:12 PM
DFarist DFarist is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Jul 2003
Posts: 16 DFarist User rank is Just a Lowly Private (1 - 20 Reputation Level) 
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

Reply With Quote
  #19  
Old March 25th, 2004, 05:10 PM
DFarist DFarist is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Jul 2003
Posts: 16 DFarist User rank is Just a Lowly Private (1 - 20 Reputation Level) 
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.

Reply With Quote
  #20  
Old March 25th, 2004, 05:54 PM
Grim Archon's Avatar
Grim Archon Grim Archon is offline
Mini me.
Dev Shed Novice (500 - 999 posts)
 
Join Date: Nov 2003
Location: Cambridge, UK
Posts: 783 Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)  Folding Points: 1488 Folding Title: Novice Folder
Time spent in forums: 3 Days 2 h 15 m 57 sec
Reputation Power: 12
Send a message via MSN to Grim Archon
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

Reply With Quote
  #21  
Old March 29th, 2004, 11:35 PM
TheBlackMamba TheBlackMamba is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Apr 2003
Posts: 25 TheBlackMamba User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Send a message via AIM to TheBlackMamba Send a message via Yahoo to TheBlackMamba
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.

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython 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 
Rate This Thread:


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

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


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap