数学上面的定义:迭代公式就是指用现在的值,代到一个公式里面,算出下一个值,再用下一个值代入公式,如此往复地代。比如:x=(x+2/x)/2 你随便拿一个x=10代入,得x=(10+2/10)/2=5.1,再代进去x=(5.1+2/5.1)/2=2.746,再代入得1.737,以此类推。
在python中,迭代式也可以是递归的调用,下面给你举个例子:
def f(n):
if n == 0 or n == 1 or n == 2: return 1
else: return f(n-1) + f(n-2)
这就是一个简单的第n项斐波那契数的求法,这里就用的是迭代式。另外的例子就是牛顿迭代法,采用逐次渐进的效果求出n的开方数,下面是例子:
def f(guess):
return guess ** 2
def fd(guess):
return 2 * guess
def SquareRootNR(x, epsilon):
guess = x / 2.0
diff = f(guess) – x
ctr = 1
while abs(diff) > epsilon and ctr
guess = guess – diff / fd(guess)
diff = f(guess) – x
ctr += 1。