Representation of floats (-> Mark Dickinson?)

casevh casevh at gmail.com
Wed Sep 7 05:58:29 CEST 2011


On Sep 6, 6:37 am, jmfauth <wxjmfa... at gmail.com> wrote:
> This is just an attempt to put thehttp://groups.google.com/group/comp.lang.python/browse_thread/thread/...
> discussion at a correct level.
>
> With Python 2.7 a new float number representation (the David Gay's
> algorithm)
> has been introduced. If this is well honored in Python 2.7, it
> seems to me, there are some missmatches in the Py3 series.
>
> >>> sys.version
>
> '2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit
> (Intel)]'
>
> >>> 0.1
> 0.10000000000000001
> >>> print 0.1
> 0.1
> >>> 1.1 * 1.1
> 1.2100000000000002
> >>> print 1.1 * 1.1
> 1.21
> >>> print repr(1.1 * 1.1)
> 1.2100000000000002
>
> >>> sys.version
>
> 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]
>
>
>
> >>> 0.1
> 0.1
> >>> print 0.1
> 0.1
> >>> 1.1 * 1.1
> 1.21
> >>> print 1.1 * 1.1
> 1.21
> >>> print repr(1.1 * 1.1)
> 1.2100000000000002
>

I tried this with the same version of Python and I get:

>>> sys.version
'2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]'
>>> 1.1 * 1.1
1.2100000000000002
>>> print 1.1 * 1.1
1.21
>>> print repr(1.1 * 1.1)
1.2100000000000002
>>>

> >>> sys.version
>
> '3.1.4 (default, Jun 12 2011, 15:05:44) [MSC v.1500 32 bit (Intel)]'>>> 0.1
> 0.1
> >>> print(0.1)
> 0.1
> >>> 1.1 * 1.1
> 1.2100000000000002
> >>> print(1.1 * 1.1)
> 1.21
> >>> print(repr(1.1 * 1.1))
> 1.2100000000000002
> >>> '{:g}'.format(1.1 * 1.1)
>
> '1.21'
>
> >>> sys.version
>
> '3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)]'
>
> >>> 0.1
> 0.1
> >>> print(0.1)
> 0.1
> >>> 1.1 * 1.1
> 1.2100000000000002
> >>> print (1.1 * 1.1)
> 1.2100000000000002
> >>> print(repr((1.1 * 1.1)))
> 1.2100000000000002
>
> >>> '{:g}'.format(1.1 * 1.1)
> '1.21'
>

I get same results as you do for Python 3.1.4 and 3.2.2. IIRC, Python
3.2 changed (for floats) __str__ to call __repr__. That should explain
the difference between 3.1.4 and 3.2.2

Also note that 1.1 * 1.1 is not the same as 1.21.

>>> (1.1 * 1.1).as_integer_ratio()
(5449355549118301, 4503599627370496)
>>> (1.21).as_integer_ratio()
(1362338887279575, 1125899906842624)

This doesn't explain why 2.7.2 displayed a different result on your
computer. What do you get for as_integer_ratio() for (1.1 * 1.1) and
(1.21)?

casevh


> jmf




More information about the Python-list mailing list