Skip to content
Advertisement

How is python’s float.__eq__ implemented in the language?

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:

JavaScript

So it just creates two C doubles from the float objects, then (skipping all the int handling stuff):

JavaScript

It just does a C-level == comparison, ultimately. So it does not do math.isclose(float_a, float_b). underneath the hood.

Advertisement