Created
December 28, 2016 09:08
-
-
Save Mekire/6b15434008069072e81982a3e82b63ca to your computer and use it in GitHub Desktop.
This file contains hidden or 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
from __future__ import division | |
class BoundedFloat(float): | |
def __new__(self, value, minimum, maximum): | |
return float.__new__(self, value) | |
def __init__(self, value, minimum, maximum): | |
if not (minimum <= value <= maximum): | |
raise ValueError("Minimum must be less than or equal to value which" | |
" must be less than or equal to maximum.") | |
float.__init__(value) | |
self.minimum = minimum | |
self.maximum = maximum | |
def limit(self, new): | |
if new < self.minimum: | |
result = BoundedFloat(self.minimum, self.minimum, self.maximum) | |
elif new > self.maximum: | |
result = BoundedFloat(self.maximum, self.minimum, self.maximum) | |
else: | |
result = BoundedFloat(new, self.minimum, self.maximum) | |
return result | |
def __iadd__(self, other): | |
new = self + other | |
return self.limit(new) | |
def __isub__(self, other): | |
new = self - other | |
return self.limit(new) | |
def __imul__(self, other): | |
new = self * other | |
return self.limit(new) | |
def __itruediv__(self, other): | |
new = self / other | |
return self.limit(new) | |
def __ifloordiv__(self, other): | |
new = self // other | |
return self.limit(new) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment