Reputation: 9
I'm learning python and as practice I wrote some code to find the derivative of a user defined function. The code is as follows.
def fx(value, function):
x = value
return eval(function)
input_function = raw_input('Input your function using correct python syntax: ')
def derivative_formula(x, h):
(fx(x - h, input_function) - fx(x + h, input_function)) / 2 * h
def derivative_of_x(x):
error = 0.0001
h = 0.1
V = derivative_formula(x, h)
h = h / 2
derivative_estimate = derivative_formula(x, h)
while abs(derivative_estimate - V) < error:
V = derivative_formula(x, h)
h = h / 2
derivative_estimate = derivative_formula(x, h)
return derivative_estimate
x1 = float(raw_input('Where do you want to calculate the derivative?'))
return derivative_of_x(x1)
The full error code is as follows
Traceback (most recent call last):
File "Derivative.py", line 25, in <module>
print derivative_of_x(x1)
File "Derivative.py", line 17, in derivative_of_x
while abs(derivative_estimate - V) - error:
TypeError: Unsupported operand type(s) for -: 'NoneType' and 'NoneType'
Upvotes: 1
Views: 729
Reputation: 76194
You forgot to return anything from your derivative_formula
function. Try:
def derivative_formula(x, h):
return (fx(x - h, input_function) - fx(x + h, input_function)) / 2 * h
Also, if you are trying to divide by 2h, you'll need an additional parenthesis.
def derivative_formula(x, h):
return (fx(x - h, input_function) - fx(x + h, input_function)) / (2 * h)
And I think you want to reverse the two function calls there.
def derivative_formula(x, h):
return (fx(x + h, input_function) - fx(x - h, input_function)) / (2 * h)
Upvotes: 2
Reputation: 2488
Your derivative_formula
has no return
statement which in python defaults to return None
. Hence when you call abs(derivative_estimate - V)
you are effectively subtracting a NoneType
object (V
) from another NoneType
object.
What you need is the return statement in derivative_formula
:
def derivative_formula(x, h):
res = (fx(x - h, input_function) - fx(x + h, input_function)) / 2 * h
return res
Upvotes: 0