for / while else doesn't make sense

Steven D'Aprano steve at pearwood.info
Tue May 24 13:44:22 EDT 2016


On Tue, 24 May 2016 08:54 pm, Jon Ribbens wrote:

> On 2016-05-24, Steven D'Aprano <steve at pearwood.info> wrote:
>> On Tue, 24 May 2016 03:09 am, Jon Ribbens wrote:
>>> On 2016-05-23, Steven D'Aprano <steve at pearwood.info> wrote:
[...]
>> In Australia, we have an 11% consumption tax, the GST. I cannot tell you
>> how many times I've needed to add a 1 cent "Rounding" amount on invoices
>> to get the results to work out correctly.
> 
> Indeed. Using floats for currency calculations is one of the many
> traps they present, and an excellent example of why their use should
> not be encouraged.

How do you know the software uses floats?

I haven't told you the name of the accounting software I use. It is
proprietary software, so the source code is unavailable. Unless you work
for the company in question, I doubt you would know what implementation
they use.

But worse, you ignored my example where I showed that using integer
arithmetic also generates the same kind of off by one cent errors.


>> E.g. if an item costs $17 including tax, then you have a choice in
>> rounding the tax-free cost down to $15.31 or up to $15.32,
> 
> I very much doubt that you have any such choice - it will usually
> be specified by the tax regulations.

This is not a matter about the GST legislation. It is a matter of
mathematics that using integer or fixed point arithmetic is vulnerable to
the same sorts of rounding errors as floating point arithmetic.

(Using integers is equivalent to fixed point arithmetic with an implicit
decimal point.)


> The correct way to do currency stuff is either integers or Decimal.

You're repeating my words back at me. I already said that.


>> Using integers in this case is not only *harder* than using floats, but
>> it's more likely to go wrong. Because integer division always rounds
>> down, errors accumulate faster than with floats, where calculations will
>> be correctly rounded to minimize the error.
> 
> You are falling into the float trap again. This is not how you do
> accounting.

Did you look at the code I showed? I'm not using floats. I'm using integers,
counting in cents.

If you're just going to automatically gainsay everything I say without even
reading what I say first, well, you're no John Cleese.



-- 
Steven




More information about the Python-list mailing list