这与实施无关。这是关于运算符的语义。无论实现如何,// 运算符都需要为您提供应用于浮点数时看到的结果,并且这些结果确实是正确的(对于浮点数)。如果您不想要这些结果,那么浮点数可能是您正在做的错误的工具。
1 // 0.2 给出浮点数,表示其参数的商的确切值的下限。但是,右侧参数的值与您输入的值不完全一致。右侧参数的值是 64 位 IEEE 二进制浮点可表示的最接近 0.2 的值,略高于 0.2:
>>> import decimal
>>> decimal.Decimal(0.2)
Decimal('0.200000000000000011102230246251565404236316680908203125')
因此,商的确切值略小于 5,因此1 // 0.2 为您提供4.0。
1 / 0.2 给你5.0 因为商的确切值不能表示为浮点数。结果需要四舍五入,四舍五入为5.0。 // 不执行此舍入;它计算精确值的下限,而不是四舍五入的浮点数的下限。 (// 的结果可能需要四舍五入,但这是不同的四舍五入。)
话虽如此,实现需要比floor(x / y) 更复杂,因为那样会给出错误的结果。 CPython 的 // 实现基于 fmod 的浮点数。您可以在 CPython 源代码库中的 Objects/floatobject.c 中查看实现。
static PyObject *
float_divmod(PyObject *v, PyObject *w)
{
double vx, wx;
double div, mod, floordiv;
CONVERT_TO_DOUBLE(v, vx);
CONVERT_TO_DOUBLE(w, wx);
if (wx == 0.0) {
PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
return NULL;
}
PyFPE_START_PROTECT("divmod", return 0)
mod = fmod(vx, wx);
/* fmod is typically exact, so vx-mod is *mathematically* an
exact multiple of wx. But this is fp arithmetic, and fp
vx - mod is an approximation; the result is that div may
not be an exact integral value after the division, although
it will always be very close to one.
*/
div = (vx - mod) / wx;
if (mod) {
/* ensure the remainder has the same sign as the denominator */
if ((wx < 0) != (mod < 0)) {
mod += wx;
div -= 1.0;
}
}
else {
/* the remainder is zero, and in the presence of signed zeroes
fmod returns different results across platforms; ensure
it has the same sign as the denominator. */
mod = copysign(0.0, wx);
}
/* snap quotient to nearest integral value */
if (div) {
floordiv = floor(div);
if (div - floordiv > 0.5)
floordiv += 1.0;
}
else {
/* div is zero - get the same sign as the true quotient */
floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
}
PyFPE_END_PROTECT(floordiv)
return Py_BuildValue("(dd)", floordiv, mod);
}
static PyObject *
float_floor_div(PyObject *v, PyObject *w)
{
PyObject *t, *r;
t = float_divmod(v, w);
if (t == NULL || t == Py_NotImplemented)
return t;
assert(PyTuple_CheckExact(t));
r = PyTuple_GET_ITEM(t, 0);
Py_INCREF(r);
Py_DECREF(t);
return r;
}
其他参数类型将使用其他实现,具体取决于类型。