Decimals not equalling themselves (e.g. 0.2 = 0.2000000001)

Fuzzyman fuzzyman at gmail.com
Sun Aug 3 18:51:05 EDT 2008


On Aug 3, 3:02 pm, CNiall <cni... at icedcerulean.com> wrote:
> I am very new to Python (I started learning it just yesterday), but I
> have encountered a problem.
>
> I want to make a simple script that calculates the n-th root of a given
> number (e.g. 4th root of 625--obviously five, but it's just an example
> :P), and because there is no nth-root function in Python I will do this
> with something like x**(1/n).
>
> 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.25
> 0.25
>  >>> 0.125
> 0.125
>  >>> 0.2
> 0.20000000000000001
>  >>> 0.33
> 0.33000000000000002
>
> 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'. How might I make Python recognise 0.2 as 0.2
> and not 0.20000000000000001?
>
> This discrepancy is very minor, but it makes the whole n-th root
> calculator inaccurate. :\

You're using floating point numbers and not decimals. For the
precision of decimals use the Python standard library decimal module.

As others have noted, the accuracy issue with floating point numbers
is enshrined in their implementation at the platform level and has
nothing to do with Python.

Michael Foord
--
http://www.ironpythoninaction.com/



More information about the Python-list mailing list