2015-01-07 50 views
1

我在Python 2.7中遇到了一些類型錯誤,包括一些遞歸代碼。下面的代碼本質上是一個黎曼積分,它將曲線下面的矩形區域相加。當'step'爲0.25或更大時,它可以很好地工作,但是當它小於0.25時會出現類型錯誤。爲什麼會發生這種情況,我該如何解決?已解決。在Python 2.7中輸入一些簡單遞歸代碼的錯誤

File "/home/i/PycharmProjects/6.00.1x/prob3/radiationExposure.py", line 25, in radiationExposure 
return f(stop - step) * step + radiationExposure(start, (stop - step), step)  

類型錯誤::不支持的操作數類型(一個或多個)爲+:「浮動」和「NoneType」

我的代碼如下所示爲代碼的最後線路中發生

以下錯誤:

def f(x): 
    import math 
    return 10*math.e**(math.log(0.5)/5.27 * x) 

def radiationExposure(start, stop, step): 

''' 
    Computes and returns the amount of radiation exposed 
    to between the start and stop times. Calls the 
    function f to obtain the value of the function at any point. 

    start: integer, the time at which exposure begins 
    stop: integer, the time at which exposure ends 
    step: float, the width of each rectangle. You can assume that 
     the step size will always partition the space evenly. 

    returns: float, the amount of radiation exposed to 
     between start and stop times. 
    ''' 

    if stop - step == start: 
     return f(stop - step) * step 
    elif stop - step > start: 
     return f(stop - step) * step + radiationExposure(start, (stop - step), step) 

注意道德倫理的人:這是爲了滿足我自己的好奇心。 edx.org上的歸檔MIT課程沒有等級,並且此問題不需要遞歸代碼。

+0

當您的問題中給出的函數'radiationExposure'在'stop-step khelwood

回答

1

在您的問題中給出的函數radiationExposure返回Nonestop-step < start,因爲既不符合if條件。

if stop - step == start: 
    return f(stop - step) * step 
elif stop - step > start: 
    return f(stop - step) * step + radiationExposure(start, (stop - step), step) 
# If the execution reaches this point and the function ends, it will return None 

如果你期待算術給你確切stop-step==start,那麼就不要使用浮點變量,因爲它們是近似值。

如果不是有:

if stop - step <= start: 
    return f(stop - step) * step 
else: 
    return f(stop - step) * step + radiationExposure(start, stop - step, step) 

這將至少確保函數返回的數量,而不是None

+0

這很有道理。感謝您花時間幫助我,khelwood。 – istinson