Advertisement
Guest User

Untitled

a guest
Jul 26th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. import math
  2. import sys
  3.  
  4. class HarmonicGenerator(object):
  5. """docstring for HarmonicGenerator"""
  6. def __init__(self):
  7. super(HarmonicGenerator, self).__init__()
  8. self.n = 0
  9.  
  10. def __next__(self):
  11. return self.next()
  12.  
  13. def next(self):
  14. self.n = self.n + 1
  15. result = 1.0/self.n
  16. return result
  17.  
  18. def __iter__(self):
  19. return self
  20.  
  21.  
  22. def compute(target, precision):
  23. pos = HarmonicGenerator()
  24. neg = HarmonicGenerator()
  25. acc = 0
  26.  
  27. for x in pos:
  28. acc = acc + x
  29. if acc > target:
  30. val = neg.next()
  31. acc = acc - val
  32. elif math.fabs(acc - target) < precision:
  33. break
  34.  
  35. print 'Computed :', acc
  36. print 'Actual :', math.pi
  37. print 'Iterations :', pos.n
  38. print 'Negative :', neg.n
  39.  
  40. def main():
  41. args = sys.argv[1:]
  42. target = int(args[0])
  43. precision = float(args[1])
  44.  
  45. compute(target, precision)
  46.  
  47. if __name__ == '__main__':
  48. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement