Skip to content

Instantly share code, notes, and snippets.

@Mekire
Created December 28, 2016 09:08
Show Gist options
  • Save Mekire/6b15434008069072e81982a3e82b63ca to your computer and use it in GitHub Desktop.
Save Mekire/6b15434008069072e81982a3e82b63ca to your computer and use it in GitHub Desktop.
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