Created
April 2, 2013 09:04
-
-
Save kachayev/5290934 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| # 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