Created
January 9, 2015 12:06
-
-
Save jsbueno/1e62be882639a13180f6 to your computer and use it in GitHub Desktop.
DeltaFloat
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
# coding: utf-8 | |
class DeltaFloat(float): | |
def __new__(cls, value, delta=0.0001): | |
self = float.__new__(cls, value) | |
self.delta = delta | |
return self | |
def __eq__(self, other): | |
x = float(self) | |
delta = self.delta | |
if x - delta <= float(other) <= x + delta: | |
return True | |
return False | |
def __lt__(self, other): | |
return float(self) + self.delta < float(other) | |
def __le__(self, other): | |
return float(self) - self.delta <= float(other) | |
def __gt__(self, other): | |
return float(self) - self.delta > float(other) | |
def __ge__(self, other): | |
return float(self) + self.delta >= float(other) |
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
A naive float derived class that have an implicit "delta" for comparisons - | |
this can overcome rounding errors in simple operations while keeping the code | |
easy to read. | |
Note that operations with numbers of this class will yield "normal" floats - | |
those should be "cast" back to DeltaFloat to keep their features. | |
Note: this is not designed for transparent/heavy-duty math work: | |
a proper implementation implementing all methods in numbers.Real would be needed for that. | |
``` | |
>>> a = DeltaFloat(4.31, delta=0.01) | |
>>> a == 4.32 | |
False | |
>>> a == 4.315 | |
True | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment