strings (dollar.cents) into floats

Lawrence D'Oliveiro ldo at geek-central.gen.new_zealand
Sat Sep 1 04:13:30 CEST 2007


In message <46d75cf3$0$7698$9b4e6d93 at newsspool2.arcor-online.net>, Wildemar
Wildenburger wrote:

> But what use is there for floats, then? When is it OK to use
> them?

Floating-point numbers are useful when you have to deal with very large and
very small amounts at the same time. In using them, you must understand
something about how rounding errors work, e.g.

1) Addition of a lot of very precise quantities together will produce a
less-precise quantity:

    >>> x = 0.1
    >>> x
    0.10000000000000001
    >>> for i in range(0, 1000000) : x += 0.1
    ...
    >>> x
    100000.10000133289

(Note the original quantity was precise to over 16 figures, the accumulated
total to less than 7.)

2) Subtraction of two nearly-equal quantities will also reduce precision:

    >>> 1.0 / 1000
    0.001
    >>> 1.0 / 1001
    0.000999000999000999
    >>> 1.0 / 1000 - 1.0 / 1001
    9.9900099900102068e-07

(Again, note the drop from about 15 figures of precision down to about 12.)

In terms of currency amounts, if you're only doing additions and
subtractions, then usual practice would be to work in integer cents/pence,
and format as dollars/euros/pounds/whatever and cents/pence only for
display and user input. That way you avoid the above rounding problems.

But if you're doing multiplications and divisions (e.g. currency
conversions, taxation, interest computations, futures, derivatives etc),
then it doesn't really matter. You're going to get rounding errors anyway,
and floating point will probably let you manage them better than integers
will.



More information about the Python-list mailing list