Created
June 15, 2024 23:08
-
-
Save brandondrew/bd64d01d058135f711d81fb3ce719018 to your computer and use it in GitHub Desktop.
Safely compare floats
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## you presumably already know that this returns false, because of the way floats are stored: | |
0.1 + 0.2 == 0.3 | |
# => false | |
# we can create a more useful way of comparing floats that matches what humans would expect: | |
class Float | |
def =~(number, tolerance = 0.0001) | |
(self - number).abs < tolerance | |
end | |
end | |
## here's an example of typical usage: | |
0.1 + 0.2 =~ 0.3 | |
# => true | |
## if you need to change the tolerance, | |
## use a dot like with normal methods: | |
(0.1 + 0.2).=~ 0.3, 0.00000000001 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment