Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use math.isclose Instead of Direct Equality for Floats #453

Merged

Conversation

pixeebot[bot]
Copy link
Contributor

@pixeebot pixeebot bot commented May 7, 2024

In most programming languages, floating point arithmetic is imprecise due to the way floating point numbers are stored as binary representations. Moreover, the result of calculations with floats can vary based on when rounding happens. Using equality or inequality to compare floats or their operations will almost always be imprecise and lead to bugs.

For these reasons, this codemod changes any operations involving equality or inequality with floats to the recommended math.isclose function. This codemod uses the default parameter values rel_tol=1e-09 and abs_tol=0.0 but makes them explicit as a starting point for you to consider depending on your calculation needs.

Our changes look like the following:

+import math
+
 def foo(a, b):
-    return a == b - 0.1
+    return math.isclose(a, b - 0.1, rel_tol=1e-09, abs_tol=0.0)
More reading

I have additional improvements ready for this repo! If you want to see them, leave the comment:

@pixeebot next

... and I will open a new PR right away!

🧚🤖Powered by Pixeebot (codemod ID: pixee:python/fix-float-equality)

@pixeebot pixeebot bot requested a review from a team as a code owner May 7, 2024 03:46
@tjs-intel tjs-intel merged commit 377b8f6 into main May 7, 2024
40 checks passed
@tjs-intel tjs-intel deleted the pixeebot/drip-2024-05-07-pixee-python/fix-float-equality branch May 7, 2024 14:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant