Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Last active April 30, 2016 06:36
Show Gist options
  • Save louisswarren/7fde2fd63d4893c664b629f50eec8423 to your computer and use it in GitHub Desktop.
Save louisswarren/7fde2fd63d4893c664b629f50eec8423 to your computer and use it in GitHub Desktop.
Guess what a function converges to
import itertools
def adjacent_pairs(g):
a, b = itertools.tee(g)
next(b)
return zip(a, b)
def converge(f, vals, e=1e-9):
for a, b in adjacent_pairs(vals):
if abs(f(a) - f(b)) < e:
return f(b)
# Example: show limit definition for e works for n -> -infinity too
def e_approx(x):
return lambda n: (1 + x/n) ** n
# Start at -2 to avoid division by zero
print(converge(e_approx(1), itertools.count(-2, -1)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment