5 Comments
May 31Liked by Abhinav Upadhyay

Excellent article, and I'm delighted to find Python People on Substack (which I joined recently). I was beginning to think it was mostly writers and philosophers. In my experience, it's not uncommon to compare integers and floats in a language like Python, but they're usually reasonable values nowhere near edge cases. I do try to be aware of numeric type, though -- all sorts of nasty things happen when you don't. (Python annotations are helpful in this regard.)

I have to say, it's a bit eerie seeing:

>>> 9007199254740992. == 9007199254740993.

True

Ouch! Of course:

>>> float(9007199254740993) == 9007199254740993.

True

Which is why I tend to cast possible integer values to floats.

Expand full comment
author

Thanks Wyrd!

Yes, i think seasoned programmers are weary of these pitfalls of floating points and prefer to do explicit casts. But this was interesting to see how python behaves differently than other languages.

Expand full comment
May 31Liked by Abhinav Upadhyay

Python's floating-point comparison intricacies are fascinating! The IEEE-754 standard's limitations and Python's infinite precision integers create unexpected results, highlighting the complexities of floating-point arithmetic in different programming languages. Your deep dive into CPython's comparison algorithm sheds light on these nuances effectively.

Expand full comment

Thank you for the explanation. When does it make sense to check whether an integer and a floating point number are equal? I can’t remember the last time I’ve done that.

Expand full comment
author

I think the OP in the tweet had some test cases that run fine in a statically typed language. He is a pytorch dev so most probably he had some tests in C++. But the same thing failed for him in python.

In general, I never do a direct comparison with floats, I make sure I'm either doing explicit conversion of the int to float or I use a library which will handle all the issues.

Expand full comment