[Tutor] Decimals 'not equal to themselves' (e.g. 0.2 equals0.200000001)

Alan Gauld alan.gauld at btinternet.com
Sun Aug 3 17:44:46 CEST 2008

"CNiall" <cniall at icedcerulean.com> wrote

> However, with some, but not all, decimals, they do not seem to 
> 'equal themselves'. This is probably a bad way of expressing what I 
> mean, so I'll give an example:
> >>> 0.5
> 0.5
> >>> 0.2
> 0.20000000000000001

> As you can see, the last two decimals are very slightly inaccurate. 
> However, it appears that when n in 1/n is a power of two, the 
> decimal does not get 'thrown off'.

And that is the clue. Computers represent data as binary, ie powers
of two. If a number cannot be expressed exactly as a power of two
then a computer (any binary computer!) cannot represent the number
exactly. It is the same in "natural" arithmetic where we use base 10.
We cannot exactly represent numbers like 1/3 as a decimal number
we have to approximate to 0.33333333.... Likewise with 1/7 etc.

In most cases the approximation is "good enough" and we just live
with it. (But its not a good idea to use floating point numbers to
represent money!). If you do need exact numbers you can use the
decimal module which will do what you want but at the expense
of adding complexity.

> How might I make Python recognise 0.2 as 0.2 and not 
> 0.20000000000000001?

Mostl;y it won;t matter, what you will want is to be able to print
it as 0.2. You can do this in a number of ways but the most flexible
is to use a format string:

>>> x = 0.2
>>> print "%6f" % x

The percent inside the string is a marker which is substituted
by the value after the percent outside the string (ie x in this case)
The number following the first % is the length of
representation - 6 chars in this case.

There are several other numbers and symbols you can use to
coerce the representation to be as you wish - left/roight aligned,
leading zeros, scientific notation etc

Search the Python docs for "format" and you should find the

The other thing to watch is when comparing float values.

>>> y = 1 - 0.8
>>> y == x
>>> e = 0.0000000001
>>> x-e < y < x+e

You can find out more about format stringsin the Simple Sequences
topic of my tutorial.
You can find out a little bit more about floating point numbers in the
Raw Data topic of my tutorial under the heading Real Numbers.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list