2017-01-01 40 views
-2

我正試圖編寫一個程序,該程序應該重複平滑值提高到2,稱爲使用smoothing_five_times = repeatedly_smooth(lambda x: x**2, 5),其中第二個參數是n次。在Python中重複lambda函數n次,錯誤的值?

def repeatedly_smoothed(func, n): 
    return repeat(lambda x: ((func(x-0.001) + func(x) + func(x+0.001))/3), n) 

def repeat(f, n): 
    if n==0: 
     return (lambda x: x) 
    return (lambda x: f (repeat(f, n-1)(x))) 

它工作得很好,對於n = 1,但是x的值高不可收拾。

smooth_one_times(10) 
100.00000066666666 
smooth_two_times(10) 
10000.000134 

第二個應該返回100.0000013,我只是似乎無法得到它的工作。除以10,n或幾乎任何東西都可以得到遠離我想要的值的值。我正在犯的是什麼初學者錯誤?

+2

你把在10中,你得到100.如果你遞歸,你輸入100,並且應該輸出10000,這就是你所報告的。所以我不確定你在做什麼...... –

+0

什麼是'smooth_one_times'和'smooth_two_times'? –

+0

'repeat'本身似乎很好。 –

回答

0

如果定義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 
0

目前尚不清楚smooth_one_timessmooth_two_times究竟是什麼。但我會告訴你我(原)的定義:

def smooth_one_time(k): 
    return repeatedly_smoothed(lambda x: x ** 2, 1)(k) 

def smooth_two_time(k): 
    return repeatedly_smoothed(lambda x: x ** 2, 2)(k) 

如果以下代替(你只是沒有正確正火),我想你會得到你想要什麼:

def smooth_one_time(k): 
    return repeatedly_smoothed(lambda x: x ** 2, 1)(k)/repeat(lambda x: x**2, 1)(10) * 100 

def smooth_two_time(k): 
    return repeatedly_smoothed(lambda x: x ** 2, 2)(k)/repeat(lambda x: x**2, 2)(10) * 100 

根據需要,smooth_two_time(10)的第二個定義輸出100.00000134smooth_one_time的兩個定義在數學上都是相同的,因爲repeat(lambda x: x**2, 1)(10) * 100 == 1,但出於教學原因並希望您能看到一般模式,我將其包含在內。在不明確的情況下,它很好地概括爲:

def smooth_n_times(n, k): 
    return repeatedly_smoothed(lambda x: x ** 2, n)(k)/repeat(lambda x: x ** 2, n)(10) * 100 

但是,要小心。這很快溢出。 smooth_n_times(8, 10)輸出100.00008576。我的機器上溢出了smooth_n_times(9, 10)

HTH。