[Tutor] Some questions about my yen-USD.py

Kent Johnson kent37 at tds.net
Mon Sep 18 14:20:35 CEST 2006


Dick Moores wrote:
> I'm baaaack!
> 
> I kept getting ideas for what I (and some of you) thought was a 
> finished yen-USD.py. And some of the good advice I got was to move on 
> to other things. I did for a while, but I kept thinking up new 
> revisions. The script has more than doubled in length. I'd previously 
> posted v4 at <http://www.rcblue.com/Python/yen-USD-v3.txt>.
> 
> Here's v10: <http://www.rcblue.com/Python/yen-USD-v10.txt>
> 
> New functions:
> again()
> divide2StringDecimals()
> multiply2StringDecimals()
> roundNumber() -- replaced setPrecision()
> printVariablesNotChanging()
> formatNumber()
> removeCommasFromNumbers()
> 
> rather radically revised function:
> again()  -- offers several more choices
> 
> The most important change is that because I realized I wanted the 
> program to be a general solution and give accurate answers for even 
> very large amounts of Yen or USD, I decided to operate with (number) 
> strings only, except when necessary in getRate() and getAmount() to 
> error check user inputs. Those floats are not used in the 
> calculations of Yen or USD.

You have greatly underused Decimal - it is capable of multiplication and 
division of fractional quantities directly:

In [1]: from decimal import Decimal as D

In [2]: x=D('1.23')

In [3]: y=D('4.5')

In [4]: x*y
Out[4]: Decimal("5.535")

In [5]: x/y
Out[5]: Decimal("0.2733333333333333333333333333")
> 
> The most difficult function for me to write was roundNumber(), which 
> of course couldn't rely on the use of the built-in round() or the 
> formatting of strings (see the line "format = "%." + str(precision) + 
> 'f'" in setPrecision() in v3).  Lack of experience with the slicing 
> of lists caused many headaches. I didn't succeed in debugging until I 
> put in print statements wherever a value changes, and trying many 
> different integer strings and places (the arguments of 
> roundNumber()). A good lesson, I think.

The recipes page in the docs for Decimal include a moneyfmt() function 
that rounds to a specified number of places and inserts a separator char.

Kent

> 
> I hope some of the Tutors will take a look at the new functions, 
> especially roundNumber().
> Did I just reinvent the wheel?

Yes :-)

> Should it be broken up into more sub-functions (there's only one now)?
> It works, but is it Pythonic? Etc.
> 
> I'm also curious about multiply2StringDecimals() and divide2StringDecimals().
> Again, am I reinventing the wheel with these?
> Is there a simpler way to multiply and divide big decimals with precision?
> 
> Thanks in advance,
> 
> Dick Moores
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 




More information about the Tutor mailing list