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

Add new Lint/FloatComparison cop #8432

Merged
merged 1 commit into from Aug 2, 2020

Conversation

fatkodima
Copy link
Contributor

This is a known fact that comparing floats is bad, so this cop checks for the presence of precise comparison of floating point numbers.

a = (0.3 * 3) + 0.1 # 0.9999999999999999
b = 1.0

a == b # false 
# bad
x == 0.1
x != 0.1

# good
(x - 0.1).abs < Float::EPSILON

# good
tolerance = 0.0001
(x - 0.1).abs < tolerance

Reference: https://www.jetbrains.com/help/resharper/CompareOfFloatsByEqualityOperator.html

@bbatsov
Copy link
Collaborator

bbatsov commented Aug 1, 2020

Great cop idea! Can you also submit a PR for this to the Ruby style guide?

@fatkodima
Copy link
Contributor Author

Updated with all suggestions.

@bbatsov bbatsov merged commit 6b36c44 into rubocop:master Aug 2, 2020
@bbatsov
Copy link
Collaborator

bbatsov commented Aug 2, 2020

Thanks!

@dvandersluis
Copy link
Member

dvandersluis commented Aug 28, 2020

Should this flag comparisons to 0 or 0.0? I don't believe there are precision issues with zero (Float#zero? is true for 0.0).

See: https://github.com/ruby/ruby/blob/c87043283ef7114db54857ae13798e3d7cb031c0/numeric.c#L1743-L1747 and https://github.com/ruby/ruby/blob/1035a3b202ee86bf2b0a1d00eefcfff0d7ab9f6b/internal/numeric.h#L137-L141

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.

None yet

4 participants