mirror of
https://github.com/python/cpython.git
synced 2025-08-30 21:48:47 +00:00
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.
This commit is contained in:
parent
ae94cf292b
commit
1e162d3753
1 changed files with 14 additions and 6 deletions
|
@ -1488,14 +1488,22 @@ builtin_round(self, args)
|
||||||
if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits))
|
if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits))
|
||||||
return NULL;
|
return NULL;
|
||||||
f = 1.0;
|
f = 1.0;
|
||||||
for (i = ndigits; --i >= 0; )
|
i = abs(ndigits);
|
||||||
|
while (--i >= 0)
|
||||||
f = f*10.0;
|
f = f*10.0;
|
||||||
for (i = ndigits; ++i <= 0; )
|
if (ndigits < 0)
|
||||||
f = f*0.1;
|
x /= f;
|
||||||
if (x >= 0.0)
|
|
||||||
return PyFloat_FromDouble(floor(x*f + 0.5) / f);
|
|
||||||
else
|
else
|
||||||
return PyFloat_FromDouble(ceil(x*f - 0.5) / f);
|
x *= f;
|
||||||
|
if (x >= 0.0)
|
||||||
|
x = floor(x + 0.5);
|
||||||
|
else
|
||||||
|
x = ceil(x - 0.5);
|
||||||
|
if (ndigits < 0)
|
||||||
|
x *= f;
|
||||||
|
else
|
||||||
|
x /= f;
|
||||||
|
return PyFloat_FromDouble(x);
|
||||||
}
|
}
|
||||||
|
|
||||||
static PyObject *
|
static PyObject *
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue