repr(complex) in Py3.1

Mark Dickinson dickinsm at gmail.com
Sat Oct 24 16:44:48 CEST 2009


On Oct 24, 3:26 pm, Stefan Behnel <stefan... at behnel.de> wrote:
> Hi,
>
> in Python 3.1.1, I get this:
>
>   Python 3.1.1 (r311:74480, Oct 22 2009, 19:34:26)
>   [GCC 4.3.2] on linux2
>   Type "help", "copyright", "credits" or "license" for more information.
>   >>> 2j
>   2j
>   >>> -2j
>   -2j
>   >>> -0-2j
>   -2j
>   >>> (-0-2j)
>   -2j
>   >>> -(2j)
>   (-0-2j)
>
> The last line differs from what earlier Python versions printed here:
[...]
> I know at least that the float repr() was modified in Py3.1, but is the
> above behaviour intentional? It certainly breaks doctests, and I don't see
> a good reason for that.

Yes, it's intentional.  The problem with the 2.6 complex repr is that
it doesn't accurately represent negative zeros, so that if you try
to eval the result you don't end up with the same complex number:

Python 2.6.1 (r261:67515, Jul  7 2009, 23:51:51)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> z = -(2j)
>>> z.real
-0.0
>>> w = complex(repr(z))
>>> w.real
0.0

This was part of a set of changes made to ensure that complex(repr(z))
round-tripping worked correctly, even when z involves negative zeros,
nans, or infinities.  (However, note that eval(repr(z)) doesn't
round-trip correctly;  that's not a problem that's easy to solve.)

Mark



More information about the Python-list mailing list