2012-04-14 128 views
2

我在使用scipy.weave.inline時遇到問題。我想編寫一個以lcenter爲中心的單位步長函數,並使用width_nm。我有兩個版本:Python版本,稱爲pm和優化函數,稱爲pm_weave,但它看起來像abs不能正常工作。請參閱下面的代碼。如果你運行它,你會得到一個窗口大小爲1的織物品種,無論輸入是什麼,所以它看起來像abs不起作用。例如,如果您移除了abs,它的工作原理與您所期望的完全相同scipy.weave.inline不按預期方式與數學庫一起工作

我該如何解決這個問題?

def pm_weave(w,lcenter,width_nm): 
    """ Return a unitstep function that is centered around lcenter with height 1.0 and width width_nm """ 
    lcenter = float(lcenter) 
    w = float(w) 
    width_nm = float(width_nm) 
    code = """ 
    #include <math.h> 
    float wl = 1.88495559215387594307758602997E3/w; 

    if(abs(lcenter-wl) < width_nm) { 
    return_val = 1.0; 
    } 
    else { 
    return_val = 0.0; 
    } 
    """ 
    res = weave.inline(code,['w','lcenter','width_nm'], 
        type_converters = weave.converters.blitz, 
        compiler = "gcc", headers=["<math.h>"] 
        ) 
    return res 



def pm(w,lcenter,width_nm): 
    """ 
    Return a unitstep function centered around lcenter [nm] with width width_nm. w 
    should be a radial frequency. 
    """ 
    return abs(600*np.pi/w - lcenter) < width_nm/2. and 1. or 0. 



plot(wavelength_list,map(lambda w:pm(toRadialFrequency(w),778,1),wavelength_list),label="Desired behaviour") 
plot(wavelength_list,map(lambda w:pm_weave(toRadialFrequency(w),778,1),wavelength_list),'^',label="weave.inline behaviour") 
ylim(0,1.5) 
show() 

回答

2

我想你可能需要在C代碼中使用fabs()而不是abs()abs()將截斷結果,而fabs()將適用於浮點運算。

+0

哇......很簡單! 謝謝!這解決了問題! – Dirklinux 2012-04-15 09:44:48