Reputation: 11
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.
Upvotes: 1
Views: 243
Reputation: 59166
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
.
Upvotes: 1