Skip to content

Instantly share code, notes, and snippets.

@louisswarren

louisswarren/converge.py

Last active Apr 30, 2016
Embed
What would you like to do?
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