Categories
Python Answers

How to compare floats for almost-equality in Python?

Spread the love

Sometimes, we want to compare floats for almost-equality in Python.

In this article, we’ll look at how to compare floats for almost-equality in Python.

How to compare floats for almost-equality in Python?

To compare floats for almost-equality in Python, we can use the math.isclose method.

For instance, we wrirew

import math
a = 5.0
b = 4.99998
is_close = math.isclose(a, b, rel_tol=1e-5)

to check if a is close b by checking if their absolute difference is 1e-5 or less.

We set the rel_tol argument to the largest absolute difference for 2 numbers to be considered close.

Conclusion

To compare floats for almost-equality in Python, we can use the math.isclose method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *