Better Programming

Advice for programmers.

Follow publication

Member-only story

The Right Way to Compare Floats in Python

David Amos
Better Programming
Published in
7 min readMar 22, 2022

Floating-point numbers are a fast and efficient way to store and work with numbers, but they come with a range of pitfalls that have surely stumped many fledgling programmers — perhaps some experienced programmers, too! The classic example demonstrating the pitfalls of floats goes like this:

Seeing this for the first time can be disorienting. But don’t throw your computer in the trash bin. This behavior is correct!

This article will show you why floating-point errors like the one above are common, why they make sense, and what you can do to deal with them in Python.

Your Computer is a Liar (Sort Of)

You’ve seen that 0.1 + 0.2 is not equal to 0.3 but the madness doesn't stop there. Here are some more confounding examples:

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

David Amos
David Amos

Written by David Amos

Professional technical writer, amateur everything else. Read my mind at https://thoughtcicles.xyz.

Responses (1)