'Why 10.5 floor divide 2.1 is equal to 4 in python [duplicate]

I found that in python, 10.5 // 2.1 == 4.0 but 11.5 // 2.3 == 5.0.

I guess the reason could be releated to the representing of float number in computer. But both 10.5 and 11.5 could be well represented while 2.1 and 2.3 cannot. So why the resule is different?

screen shot



Solution 1:[1]

I'm not really familiar with the C source of python, but poking about I think that // is implemented by:

float_floor_div(PyObject *v, PyObject *w)
{
    double vx, wx;
    double mod, floordiv;
    CONVERT_TO_DOUBLE(v, vx);
    CONVERT_TO_DOUBLE(w, wx);
    if (wx == 0.0) {
        PyErr_SetString(PyExc_ZeroDivisionError, "float floor division by zero");
        return NULL;
    }
    _float_div_mod(vx, wx, &floordiv, &mod);
    return PyFloat_FromDouble(floordiv);
}

While we could dive into _float_div_mod(), but since it looks to be the basis of python's implementation of divmod(), I just tried this:

divmod(10.5, 2.1)

Giving me:

(4.0, 2.0999999999999996)

So, the answer seems to be chocked up to Is floating point math broken?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1