使用以下参数编写函数iterate: f:一个功能 start:数字起始值 tol:数值公差(默认值1e-6) itmax:最大迭代次数(默认值1000)
从初始值开始,你的函数应该继续重复调用函数(例如y = f(y)),直到f(y)-y的绝对值小于tol或者迭代次数等于itmax。例如,如果start = 1.01,f是math.sqrt,tol = 1e-4,则序列如下所示:
在步骤6中,差值的绝对值小于容差(1e-4),因此函数返回[6,1.007777399813863]。
测试(应该都是真的):
def approx_equal(x,y,tol=1e-8):
"""helper function: test whether all elements of
x and y are equal within tolerance
"""
if len(x) != len(y):
return(False)
for i in range(len(x)):
if (abs(x[i]-y[i])>tol):
return(False)
return(True)
def disc_logist(x):
"""discrete logistic function"""
return(1.5*x*(1-x))
print(approx_equal(iterate(disc_logist,0.5),[15, 0.33333433255312184]))
print(approx_equal(iterate(disc_logist,0.5,tol=1e-8),[22, 0.33333334113969143]))
def half(x):
"""just what it says"""
return(x/2)
print(approx_equal(iterate(half,1000),[29, 9.313225746154785e-07]))
import math
print(approx_equal(iterate(math.sqrt,1.01,tol=1e-4),[6, 1.0000777399813863]))
print(approx_equal(iterate(math.cos,0),[34, 0.7390855263619245]))
print(approx_equal(iterate(math.cos,0,tol=1e-8),[46, 0.7390851366465718]))
print(approx_equal(iterate(math.cos,0,itmax=5),[5, 0.7013687736227565]))
这是我到目前为止所做的:
def iterate(f,start,tol=1e-6,itmax=1000):
"""function should keep repeating calls to the function until the absolute
value of f(y)-y is less than tol or number of iterations is equal to itmax
:f: a function
:start: a numeric starting value
:tol: a numerical tolerance
:itmax: a maximum number of iterations"""
import math
y=start
for i in range(itmax):
y_2=f(y)
if abs(y_2 - y) <tol:
return y
else:
y=y_2
答案 0 :(得分:0)
你当前问题的答案是不是返回一个数字,而是返回一个包含迭代次数和第二个答案的二元素列表 - 请注意说明(我的重点):
在步骤6中,差值的绝对值小于容差(1e-4),因此函数返回 [6,1.007777399813863] 。
def iterate(f,start,tol=1e-6,itmax=1000):
"""function should keep repeating calls to the function until the absolute
value of f(y)-y is less than tol or number of iterations is equal to itmax
:f: a function
:start: a numeric starting value
:tol: a numerical tolerance
:itmax: a maximum number of iterations"""
import math
y=start
for i in range(itmax):
y_2=f(y)
if abs(y_2 - y) <tol:
# Return the successful value - the last result, not the last input
return [i, y_2]
else:
y=y_2
# Return the next answer
return [itmax, f(y)]
这将使approx_equal()
正常工作,但我还没有完全测试它,看看是否所有结果都匹配。