I know that the best way to compare two floats for equality is usually to use math.isclose(float_a, float_b)
. But I was curious to know how python does it if you simply do float_a == float_b
.
I suppose it’s implemented in C, but what is the logic behind it ?
Advertisement
Answer
Here is the source code for float object comparisons
Essentially. It looks super complex, but that complexity is mostly in handling the case where a float
is compared to an int
(int
objects in Python are arbitrarily sized, they aren’t C-int’s wrapped in a Python object).
But for the simple case of float
and float
:
static PyObject*
float_richcompare(PyObject *v, PyObject *w, int op)
{
double i, j;
int r = 0;
assert(PyFloat_Check(v));
i = PyFloat_AS_DOUBLE(v);
/* Switch on the type of w. Set i and j to doubles to be compared,
* and op to the richcomp to use.
*/
if (PyFloat_Check(w))
j = PyFloat_AS_DOUBLE(w);
So it just creates two C double
s from the float
objects, then (skipping all the int handling stuff):
Compare:
switch (op) {
case Py_EQ:
r = i == j;
break;
case Py_NE:
r = i != j;
break;
case Py_LE:
r = i <= j;
break;
case Py_GE:
r = i >= j;
break;
case Py_LT:
r = i < j;
break;
case Py_GT:
r = i > j;
break;
}
return PyBool_FromLong(r);
It just does a C-level ==
comparison, ultimately. So it does not do math.isclose(float_a, float_b).
underneath the hood.