Nov-29-2017, 09:23 PM
Working with floats are annoying. So I change to Fraction.
from fractions import Fraction def fract10(value, width): return Fraction(value, 10 ** width) class FloatRange: def __init__(self, width, start, start_width, end=None, end_width=None, step=1): self.width = Fraction(10 ** width, 1) if end is None: self.start_width(10 ** self.width, 1) self.end_width = Fraction(10 ** start_width, 1) self.end = Fraction(start, 10 ** start_width) self.start = Fraction(1, self.width) else: self.start_width = Fraction(10 ** start_width, 1) self.end_width = Fraction(10 ** end_width, 1) self.start = Fraction(start, 10 ** start_width) self.end = Fraction(end, 10 ** end_width) self.step = Fraction(step, 10 ** width) self.start_range = self.start, self.end, self.step def __iter__(self): while self.start < self.end: yield float(self.start / self.width * self.start_width) self.start += self.step def __lt__(self, value, width): return Fraction(value, 10 ** width) <= self.start_range[0] def __gt__(self, value, width): return Fraction(value, 10 ** width) > self.start_range[1] def __contains__(self, value_tup): value, width = value_tup v = int(Fraction(value, 10 ** width) * self.width) s = int(self.start_range[0] * self.start_width) e = int(self.start_range[1] * self.end_width) step = int(self.step * self.width) return v in range(s, e, step) # or #return e > v >= s if __name__ == "__main__": frange = FloatRange(3, 450, 2, 470 , 2) print((452, 2) in frange) print((452, 3) in frange) #for i in frange: # print(i)
99 percent of computer problems exists between chair and keyboard.