[Tutor] How to correct decimal addition.

Oscar Benjamin oscar.j.benjamin at gmail.com
Sat Jan 25 22:23:07 CET 2014


On 25 January 2014 21:01, Keith Winston <keithwins at gmail.com> wrote:
>
> I think that you should probably do your math in floating point (why
> get complicated? And you might need the accuracy, for hundredths of
> dollars and interest) and then format the output to be what you want.
> Watch out for rounding.

It may not matter in this case but the key point about the Decimal
module is that it implements "decimal floating point" whereas ordinary
floats implement "binary floating point". I would prefer to use the
decimal module which can represent decimal values exactly and perform
simple decimal-type computations such as this one exactly.

Incidentally you can use the Decimal module to see how the *exact*
value of a float looks when written out in decimal digits:

>>> from decimal import Decimal as D
>>> D(0.5) # 0.5 can be represented exactly in binary FP
Decimal('0.5')
>>> D(0.1) # 0.1 cannot
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> D(3.49)
Decimal('3.4900000000000002131628207280300557613372802734375')
>>> D(3.499)
Decimal('3.499000000000000110134124042815528810024261474609375')


Oscar


More information about the Tutor mailing list