Skip to content

Instantly share code, notes, and snippets.

@deostroll
Created July 26, 2016 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deostroll/0ea8c5365ea77962204ff36f262491e5 to your computer and use it in GitHub Desktop.
Save deostroll/0ea8c5365ea77962204ff36f262491e5 to your computer and use it in GitHub Desktop.
import math
import sys
class HarmonicGenerator(object):
"""docstring for HarmonicGenerator"""
def __init__(self):
super(HarmonicGenerator, self).__init__()
self.n = 0
def __next__(self):
return self.next()
def next(self):
self.n = self.n + 1
result = 1.0/self.n
return result
def __iter__(self):
return self
def compute(target, precision):
pos = HarmonicGenerator()
neg = HarmonicGenerator()
acc = 0
for x in pos:
acc = acc + x
if acc > target:
val = neg.next()
acc = acc - val
elif math.fabs(acc - target) < precision:
break
print 'Computed :', acc
print 'Actual :', math.pi
print 'Iterations :', pos.n
print 'Negative :', neg.n
def main():
args = sys.argv[1:]
target = int(args[0])
precision = float(args[1])
compute(target, precision)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment