如果定義smooth
如下:
def smooth(f, x):
return (f(x-0.001) + f(x) + f(x+0.001))/3
那麼我認爲你想要什麼是smooth_two_times
等同於:
In [1]: smooth(lambda y: smooth(lambda x: x**2, y), 10)
Out[1]: 100.0000013333333
然而,這實際上相當於:
repeatedly_smoothed(square, 2)(10)
=> repeat(lambda x: smooth(square, x), 2)(10)
=> smooth_square(repeat(smooth_square, 1)(10))
=> smooth_square(smooth_square(10))
=> smooth_square(100.00000066666666)
=> smooth_square(10000.000134)
我們在哪裏使用的定義:
def square(x): return x**2
def smooth_square(y): return smooth(square, y)
的問題是,是平方函數的平滑版本,並且你不想重複兩次運用它(這將或多或少平方10平方)。相反,你只需要將平滑兩次迭代地應用於平方函數。
如果你想用你的repeat
做到這一點,你可以定義smooth_function
如下:
def smooth_function(f):
def smooth_f(x):
return (f(x-0.001) + f(x) + f(x+0.001))/3
return smooth_f
這是平滑給定功能的高階函數(即返回的平滑版本功能)。因此:
smooth_function(smooth_function(lambda x: x**2))
將可以適用於10,但二次函數的雙重平滑的版本中,smooth_function
這種雙重應用程序可以被改寫爲:
(repeat(smooth_function, 2))(lambda x: x**2)
這吧, repeat
構造一個高階函數,它將單個函數作爲它的參數並構造一個雙平滑版本。然後,它可以被應用到價值10
給:
In [2]: ((repeat(smooth_function, 2))(lambda x: x**2))(10)
Out[2]: 100.0000013333333
大多數括號在這裏是多餘的,所以你可以定義:
def repeatedly_smoothed(f, n):
return repeat(smooth_function, n)(f)
def smooth_two_times(x):
return repeatedly_smoothed(lambda y: y**2, 2)(x)
,並得到:
In [3]: smooth_two_times(10)
Out[3]: 100.0000013333333
你把在10中,你得到100.如果你遞歸,你輸入100,並且應該輸出10000,這就是你所報告的。所以我不確定你在做什麼...... –
什麼是'smooth_one_times'和'smooth_two_times'? –
'repeat'本身似乎很好。 –