Simple question

Chris Angelico rosuav at gmail.com
Tue Apr 15 14:27:09 EDT 2014


On Wed, Apr 16, 2014 at 4:18 AM, Phil Dobbin <phildobbin at gmail.com> wrote:
> '>>> 0.1 + 0.1 + 0.1 - 0.3
> 5.55111.....'
>
> What I'm wondering is why the first calculation that arrives at
> '5.55111...' is so far out?

There's something you're not seeing here. In full, the output I see is:

>>> 0.1 + 0.1 + 0.1 - 0.3
5.551115123125783e-17

See that bit at the end? "e-17" means "times ten to the -17th power" -
that is, move the decimal point 17 places to the left. So the actual
value is:

>>> "%50.50f"%(0.1 + 0.1 + 0.1 - 0.3)
'0.00000000000000005551115123125782702118158340454102'

It's not actually as far out as you think; in fact, that's incredibly
close to zero.

A full explanation of why floating point arithmetic does this can be
found in many places on the internet, but the main thing to note is
that it really isn't showing 5.5.

ChrisA



More information about the Python-list mailing list