[Tutor] Decimals 'not equal to themselves' (e.g. 0.2 equals 0.200000001)
thomas.pani at gmail.com
Sun Aug 3 17:32:27 CEST 2008
> 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 : 625**(1.0/4)
In : pow(625, 1.0/4)
> However, with some, but not all, decimals, they do not seem to 'equal
> 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:
The decimal module provides decimal floating point arithmetic:
In : 0.2 * 2
In : from decimal import Decimal
In : Decimal('0.2') * 2
More information about the Tutor