Python math is off by .000000000000045

Michael Torrie torriem at gmail.com
Mon Feb 27 19:53:41 EST 2012


On 02/27/2012 10:28 AM, Ethan Furman wrote:
> jmfauth wrote:
>> On 25 fév, 23:51, Steven D'Aprano <steve
>> +comp.lang.pyt... at pearwood.info> wrote:
>>> On Sat, 25 Feb 2012 13:25:37 -0800, jmfauth wrote:
>>>>>>> (2.0).hex()
>>>> '0x1.0000000000000p+1'
>>>>>>> (4.0).hex()
>>>> '0x1.0000000000000p+2'
>>>>>>> (1.5).hex()
>>>> '0x1.8000000000000p+0'
>>>>>>> (1.1).hex()
>>>> '0x1.199999999999ap+0'
>>>> jmf
>>> What's your point? I'm afraid my crystal ball is out of order and I have
>>> no idea whether you have a question or are just demonstrating your
>>> mastery of copy and paste from the Python interactive interpreter.
>>
>> It should be enough to indicate the right direction
>> for casual interested readers.
> 
> I'm a casual interested reader and I have no idea what your post is 
> trying to say.

He's simply showing you the hex (binary) representation of the
floating-point number's binary representation.  As you can clearly see
in the case of 1.1, there is no finite sequence that can store that.
You end up with repeating numbers.  Just like 1/3, when represented in
base 10 fractions (x1/10 + x2/100, x3/1000, etc), is a repeating
sequence, the number base 10 numbers 1.1 or 0.2, or many others that are
represented by exact base 10 fractions, end up as repeating sequences in
base 2 fractions.  This should help you understand why you get errors
doing simple things like x/y*y doesn't quite get you back to x.



More information about the Python-list mailing list