Skip to content

Commit 737293b

Browse files
committed
Use floats for signed zeros in the real part of repr(complex)
>>> complex(-0.0, 1) # was (-0+1j) (-0.0+1j) This doesn't break complex(str(x)) == x invariant as we had support for parsing signed 0.0's here before.
1 parent 72722e9 commit 737293b

File tree

3 files changed

+13
-8
lines changed

3 files changed

+13
-8
lines changed

Lib/test/test_complex.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -835,14 +835,14 @@ def test(v, expected, test_fn=self.assertEqual):
835835
test_fn(str(v), expected)
836836

837837
test(complex(0., 1.), "1j")
838-
test(complex(-0., 1.), "(-0+1j)")
838+
test(complex(-0., 1.), "(-0.0+1j)")
839839
test(complex(0., -1.), "-1j")
840-
test(complex(-0., -1.), "(-0-1j)")
840+
test(complex(-0., -1.), "(-0.0-1j)")
841841

842842
test(complex(0., 0.), "0j")
843843
test(complex(0., -0.), "-0j")
844-
test(complex(-0., 0.), "(-0+0j)")
845-
test(complex(-0., -0.), "(-0-0j)")
844+
test(complex(-0., 0.), "(-0.0+0j)")
845+
test(complex(-0., -0.), "(-0.0-0j)")
846846

847847
def test_pos(self):
848848
self.assertEqual(+(1+6j), 1+6j)

Objects/complexobject.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -476,8 +476,8 @@ complex_repr(PyComplexObject *v)
476476
} else {
477477
/* Format imaginary part with sign, real part without. Include
478478
parens in the result. */
479-
pre = PyOS_double_to_string(v->cval.real, format_code,
480-
precision, 0, NULL);
479+
pre = PyOS_double_to_string(v->cval.real, format_code, precision,
480+
v->cval.real? 0 : Py_DTSF_ADD_DOT_0, NULL);
481481
if (!pre) {
482482
PyErr_NoMemory();
483483
goto done;

Python/formatter_unicode.c

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1290,8 +1290,13 @@ format_complex_internal(PyObject *value,
12901290
/* Cast "type", because if we're in unicode we need to pass an
12911291
8-bit char. This is safe, because we've restricted what "type"
12921292
can be. */
1293-
re_buf = PyOS_double_to_string(re, (char)type, precision, flags,
1294-
&re_float_type);
1293+
if (re == 0.0 && copysign(1.0, re) == -1.0)
1294+
re_buf = PyOS_double_to_string(re, (char)type, precision,
1295+
flags | Py_DTSF_ADD_DOT_0,
1296+
&re_float_type);
1297+
else
1298+
re_buf = PyOS_double_to_string(re, (char)type, precision, flags,
1299+
&re_float_type);
12951300
if (re_buf == NULL)
12961301
goto done;
12971302
im_buf = PyOS_double_to_string(im, (char)type, precision, flags,

0 commit comments

Comments
 (0)