python中的迭代式什么意思?
數(shù)學(xué)上面的定義:迭代公式就是指用現(xiàn)在的值,代到一個公式里面,算出下一個值,再用下一個值代入公式,如此往復(fù)地代。比如: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中,迭代式也可以是遞歸的調(diào)用,下面給你舉個例子:
def f(n):
if n == 0 or n == 1 or n == 2: return 1
else: return f(n-1) + f(n-2)
這就是一個簡單的第n項斐波那契數(shù)的求法,這里就用的是迭代式。另外的例子就是牛頓迭代法,采用逐次漸進的效果求出n的開方數(shù),下面是例子:
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。
上一篇python38怎么裝