```1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 ``` ```""" interval.py My submission for Programming Praxis's "Interval Arithmetic" exercise; see http://programmingpraxis.com/2010/12/21/interval-arithmetic/ NOTE: requires the fractions module. GRE, 12/21/10 """ from fractions import Fraction class Interval(object): def __init__(self, x, y, centerRep = False): self.xy = (x, y) self.centerRep = centerRep return def __repr__(self): if not self.centerRep: return "Interval [%s, %s]" % (self.xy, self.xy) else: return "Interval of width %s centered at %s" % (self.xy, self.xy) def toCenter(self): newX = Fraction((self.xy + self.xy), 2) newY = Fraction((self.xy - self.xy), 2) return Interval(newX, newY, centerRep = True) def fromCenter(self): newX = self.xy - self.xy newY = self.xy + self.xy return Interval(newX, newY, centerRep = False) def __add__(self, other, centerRep = False): s = self.fromCenter() o = other.fromCenter() x = s.xy + o.xy y = s.xy + o.xy return Interval(x, y, centerRep) def __sub__(self, other, centerRep = False): s = self.fromCenter() o = other.fromCenter() x = s.xy - o.xy y = s.xy - o.xy return Interval(x, y, centerRep) def __mul__(self, other, centerRep = False): s = self.fromCenter() o = other.fromCenter() x = s.xy * o.xy y = s.xy * o.xy return Interval(x, y, centerRep) def __div__(self, other, centerRep = False): s = self.fromCenter() o = other.fromCenter() try: entries = [Fraction(a, b) for a in self.xy for b in other.xy] return Interval(min(entries), max(entries), centerRep) except ZeroDivisionError: print "Error: divison by zero in second Interval" return if __name__ == "__main__": X = Interval(1, 2) Y = Interval(3, 4) print X + Y print X - Y print X * Y print X / Y C = X.toCenter() print C print C.fromCenter() ```