[Tutor] Decimals 'not equal to themselves' (e.g. 0.2 equals 0.200000001)

Thomas Pani thomas.pani at gmail.com
Sun Aug 3 17:32:27 CEST 2008


CNiall wrote:
> 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).
> 
Side note: of course there are python built-in ways to do that. You just 
named one yourself:

In [6]: 625**(1.0/4)
Out[6]: 5.0

also:

In [9]: pow(625, 1.0/4)
Out[9]: 5.0

> However, with some, but not all, decimals, they do not seem to 'equal 
> themselves'.
> 
> 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?
> 
You just can't store 0.1 as a binary floating point.
You might want to read:
http://www.network-theory.co.uk/docs/pytut/FloatingPointArithmeticIssuesandLimitations.html
http://www.network-theory.co.uk/docs/pytut/RepresentationError.html

The decimal module provides decimal floating point arithmetic:
http://docs.python.org/lib/module-decimal.html

like in:
In [1]: 0.2 * 2
Out[1]: 0.40000000000000002

In [2]: from decimal import Decimal

In [3]: Decimal('0.2') * 2
Out[3]: Decimal("0.4")

thomas


More information about the Tutor mailing list