Created
July 26, 2016 16:09
-
-
Save deostroll/0ea8c5365ea77962204ff36f262491e5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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