Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
DeltaFloat
# 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)
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