Question:
Name Error in Python Root Finding Function. Newbie Question!?
swtbutta33
2008-09-06 08:40:07 UTC
I have the following code to find the root of an equation by entering in the formula(f), with 2 bounds(a,b) and than a tolerance(dx).


def rootsearch(f,a,b,dx):
x1= a; f1 = f(a)
x2 = a+dx; f2 = f(x2)
while f1*f2 > 0.0:
if x1 >= b: return None,None
x1= x2; f1 = f2
x2 = x1 + dx; f2 = f(x2)
else:
return x1,x2


When I try to run the code for any formula i get rootsearch(x**2, -1, 2, .5):

Traceback (most recent call last):
File "", line 1, in
rootsearch(x**2, -1, 2, .5)
NameError: name 'x' is not defined

Appreciate any help.
Three answers:
2008-09-06 08:59:36 UTC
You're getting the NameError because x is not defined. You mean to pass 'rootsearch' a function, but you are passing the result of squaring 'x', which in this place is undefined.



You have two options, you can pass in a 'lambda' or you can define a function that encompasses the function (mathematical kind) for which you want to find the root.



define this:



def square(x): return x*x



Then you can call your function like you may expect:



rootsearch(square, -1, 2, 0.5)



Or if you don't want to have to define an additional function, you call your existing function like this:



rootsearch(lambda x: x*x, -1, 2, 0.5)



A lambda is an anonymous function, it just says: "give me back a function object that takes one argument and returns that argument multiplied by itself." They are really handy for these one-off sorts of things.



Also when I ran your code, I got a problem with that 'else'. I don't think you need it here's what I have:



http://codepad.org/5QMSqG0l
2008-09-06 15:55:55 UTC
On a first reading it would appear that somehow you are passing in the string x^2 to f and that in rootsearch an attempted conversion is taking place to a numeric value but x, as a value, has never been defined.
atheistforthebirthofjesus
2008-09-06 15:59:07 UTC
I don't do Python, but it appears that your "formula" definition is missing something, or maybe has a syntax error.



I would be helpful to show WHAT you 'enter' when you try to "run"

this code.



You have an "input" problem it seems


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...