Python,最简单:
def a(n):
if n == 0: return 1
return 1 - 1 / float(a(n-1) + 3)
# limit is sqrt(3) - 1
limit = 3.0 ** 0.5 - 1.0
# get 9 digits' precision
i = 0
while abs(a(i) - limit) > 1.0e-9:
i += 1
print i
这会发出8,表明可能无法保证诸如递归消除或记忆的优化.
当然,通常我们希望在数值上而不是在分析上获得限制,因此循环的正常方式会有所不同 – 并且最好封装在更高阶函数中……:
# get a function's limit numerically
def limit(f,eps=1.0e-11):
prevIoUs_value = f(0)
next_value = f(1)
i = 2
while abs(next_value - prevIoUs_value) > eps:
prevIoUs_value = next_value
next_value = f(i)
i += 1
return next_value
非平凡循环逻辑通常最好封装在生成器中:
def next_prev(f):
prevIoUs_value = f(0)
i = 1
while True:
next_value = f(i)
yield next_value,prevIoUs_value
i += 1
prevIoUs_value = next_value
在这台发电机的帮助下,极限HOF变得更加简单:
def limit(f,eps=1.0e-11):
for next_value,prevIoUs_value in next_prev(f):
if abs(next_value - prevIoUs_value) < eps:
return next_value
注意分离是多么有用:next_prev体现了“获取函数的下一个和前一个值”的概念,仅限于处理“循环何时终止”.
最后但并非最不重要的是,itertools通常提供了一个很好的生成器替代方案,让你以快速的方式封装挑剔的迭代逻辑(虽然它确实需要一些习惯…… ;-):
import itertools
def next_prev(f):
values = itertools.imap(f,itertools.count())
prv,nxt = itertools.tee(values)
nxt.next()
return itertools.izip(prv,nxt)