1

I'm having a type error with some recursive code in Python 2.7. The code below is essentially a riemann integral, where you add up the area of rectangles underneath a curve. It works perfectly when 'step' is 0.25 or greater, but the type error occurs when it is less than 0.25. Why does this happen and how can I fix it?

The following error occurs for the last line of code:

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

TypeError: unsupported operand type(s) for +: 'float' and 'NoneType'

My code is as follows:

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)

Note to those with ethics: This is to satisfy my own curiosity. There is no grade for the archived MIT course on edx.org, and recursive code isn't required for this problem.

0

1 Answer 1

1

The function radiationExposure given in your question returns None when stop-step < start because neither of the if conditions is met.

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

If you are expecting arithmetic to give you exactly stop-step==start, then don't use floating point variables, because they are approximations.

If you instead had:

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

that would at least ensure that the function returned a number instead of None.

Sign up to request clarification or add additional context in comments.

1 Comment

That makes perfect sense. Thank you for taking the time to help me, khelwood.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.