Skip to content

Instantly share code, notes, and snippets.

@kachayev
Created April 2, 2013 09:04
Show Gist options
  • Select an option

  • Save kachayev/5290934 to your computer and use it in GitHub Desktop.

Select an option

Save kachayev/5290934 to your computer and use it in GitHub Desktop.
# python 2.7+
from itertools import dropwhile, tee, izip
def repeatfunc(f, zero):
curr = zero
while 1:
yield curr
curr = f(curr)
def pairwise(origin):
a, b = tee(origin)
next(b, None)
return izip(a,b)
def snd(origin):
it = origin if hasattr(origin, "next") else iter(origin)
next(it, None)
return next(it, None)
def square_root(n, eps=0.01):
def f(x): return (x + float(n)/x)/2
def outside((left, right)): return abs(left-right) > eps
return snd(next(dropwhile(outside, pairwise(repeatfunc(f, n)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment