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

Dick Moores rdm at rcblue.com
Mon Sep 18 16:28:04 CEST 2006


At 06:56 AM 9/18/2006, Luke Paireepinart wrote:
>Dick Moores wrote:
>>At 05:20 AM 9/18/2006, Kent Johnson wrote:
>>
>>
>>>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")
>>>
>>
>>And sqrt() as well, which I definitely thought was not possible. 
>><http://www.python.org/dev/doc/maint24/lib/node178.html>
>>
>>Well, you settled that. I don't know why I didn't see it.
>>
>Perhaps you had some preconceptions about the limits of the Decimal 
>module, and upon
>preliminary investigations something confirmed this for you, so you 
>didn't actually look in-depth
>for a way to do what you were trying to do because it seemed at 
>first glance like Decimal wasn't the right tool
>(maybe you saw an example that didn't fully utilize Decimal or something.)
>Or, alternatively, you cheated and skimmed over the docs, and didn't 
>see something important the first time around :)

A little of both, I think, but more of the former.

>>
>>>>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.
>>>
>>
>>I'd seen the recipes in the docs, but couldn't make much sense out 
>>of them. I think I can now. Or at least more sense than before.
>><http://docs.python.org/lib/decimal-recipes.html>
>>
>Yes, even though a portion of your program has functionality in the 
>Decimal module already,
>coding anything is good practice.  For example, my dream is to one 
>day write a NES emulator in Python,
>and this has already been done dozens of times in C, C++,  Java, 
>even Visual Basic.  I don't care, my goal is the same
>whether or not I'm reinventing the wheel. :)  I know of no NES 
>emulator in Python, though, so I guess i'm not really
>reinventing the wheel after all (if anyone asks, tell them I'm 
>porting that Java emulator :)

I learned a lot in spending the time I did on roundNumber().

Dick




More information about the Tutor mailing list