# L-25 MCS 507 Wed 19 Oct 2011 : flopfloats.py

# To analyze the cost of an algorithm,
# we count the number of operations.

class FlopFloat(float):
   """
   An object of the class FlopFloat records
   the number of floating-point operations
   executed to compute the float.
   """

   def __init__(self,f=0.0,n=0):
      "constructor for a flopfloat"
      self.float = f
      self.flops = n

   def __str__(self,format='%.4e'):
      """
      Uses the formatting string in the %
      to return astring representation.
      """
      return format % self.float

   def __add__(self,*other):
      "returns the result of the addition"
      if isinstance(other[0],FlopFloat):
         sum = FlopFloat(self.float + other[0].float)
         sum.flops = self.flops + other[0].flops + 1
      else:  # treat other just as ordinary number
         sum = FlopFloat(self.float + other[0])
         sum.flops = self.flops + 1
      return sum

   def __sub__(self,*other):
      "returns the result of the subtraction"
      if isinstance(other[0],FlopFloat):
         sum = FlopFloat(self.float - other[0].float)
         sum.flops = self.flops + other[0].flops + 1
      else:
         sum = FlopFloat(self.float - other[0])
         sum.flops = self.flops + 1
      return sum

   def __mul__(self,*other):
      "returns the result of the multiplication"
      if isinstance(other[0],FlopFloat):
         sum = FlopFloat(self.float * other[0].float)
         sum.flops = self.flops + other[0].flops + 1
      else:  # treat other just as ordinary number
         sum = FlopFloat(self.float * other[0])
         sum.flops = self.flops + 1
      return sum

   def __div__(self,*other):
      "returns the result of the division"
      if isinstance(other[0],FlopFloat):
         sum = FlopFloat(self.float / other[0].float)
         sum.flops = self.flops + other[0].flops + 1
      else:
         sum = FlopFloat(self.float / other[0])
         sum.flops = self.flops + 1
      return sum

   def __pow__(self,n):
      "returns the result of the power"
      sum = FlopFloat(self.float**n)
      sum.flops = self.flops + n-1
      return sum
