[Tutor] Code critique please (OOP strategy)

Roeland Rengelink r.b.rigilink@chello.nl
Tue, 01 Jan 2002 13:52:36 +0100


Timothy Wilson wrote:
> 
> On Mon, 31 Dec 2001, Sean 'Shaleh' Perry wrote:
[snip]
> > I am also curious as to why the prices are * 100 every time.  There is no
> > comment in the code for this.
> 
> All the prices are stored in cents. My understanding is that a lot of
> software that works with financial data keeps track of everything in
> cents and converts to dollars when necessary. This should help eliminate
> rounding errors.
> 

Be very carefull here,

What you do is take a price expressed as 'xxxx.xx', convert it to float
and multiply it by 100, expecting that the resulting floating point
value (the price in cents), doesn't contain rounding errors. However, on
my machine I find:

>>> for i in '0123456789':
...     for j in '0123456789':
...             f, g = float('0.'+i+j)*100, float(i+j)
...             if f != g:
...                     print f, g, repr(f), repr(g)
... 
7.0 7.0 7.0000000000000009 7.0
14.0 14.0 14.000000000000002 14.0
28.0 28.0 28.000000000000004 28.0
29.0 29.0 28.999999999999996 29.0
55.0 55.0 55.000000000000007 55.0
56.0 56.0 56.000000000000007 56.0
57.0 57.0 56.999999999999993 57.0
58.0 58.0 57.999999999999993 58.0

where f is the value in dollars*100, and g is the value in cents, and
the above snippet lists the cases for which these values are unequal

(Tim Peters would also give a real explanation about the pitfalls of FP
math, which I will not do for fear of making an ass of myself)

However, I don't think you're solving the problem from financial
software here. IIRC that problem is related to the financial rounding
rules. Consider a VAT of 15% on a purchase of 2 items of 97 cents. The
VAT on one of these items is 15 cents. So the VAT on the puchase should
be 30 cents. Contrast this with the VAT on the purchase of one item of
1.94, which is 29 cents. Since the rounding rules work on the cents
level, it is easier in financial software to express prices in cents.
But, more importantly, financial software has to be very carefull not to
take shortcuts like:

price1*frac+price2*frac --> (price1+price2)*frac

Hope this helps,

Roeland
-- 
r.b.rigilink@chello.nl

"Half of what I say is nonsense. Unfortunately I don't know which half"