8000 Implement round() slightly different, so that for negative ndigits no · python/cpython@1e162d3 · GitHub
[go: up one dir, main page]

Skip to content

Commit 1e162d3

Browse files
committed
Implement round() slightly different, so that for negative ndigits no
additional errors happen in the last step. The trick is to avoid division by 0.1**n -- multiply by 10.0**n instead.
1 parent ae94cf2 commit 1e162d3

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

Python/bltinmodule.c

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1488,14 +1488,22 @@ builtin_round(self, args)
14881488
if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits))
14891489
return NULL;
14901490
f = 1.0;
1491-
for (i = ndigits; --i >= 0; )
1491+
i = abs(ndigits);
1492+
while (--i >= 0)
14921493
f = f*10.0;
1493-
for (i = ndigits; ++i <= 0; )
1494-
f = f*0.1;
1494+
if (ndigits < 0)
1495+
x /= f;
1496+
else
1497+
x *= f;
14951498
if (x >= 0.0)
1496-
return PyFloat_FromDouble(floor(x*f + 0.5) / f);
1499+
x = floor(x + 0.5);
1500+
else
1501+
x = ceil(x - 0.5);
1502+
if (ndigits < 0)
1503+
x *= f;
14971504
else
1498-
return PyFloat_FromDouble(ceil(x*f - 0.5) / f);
1505+
x /= f;
1506+
return PyFloat_FromDouble(x);
14991507
}
15001508

15011509
static PyObject *

0 commit comments

Comments
 (0)
0