bhjghjh - 6 months ago 9
Python Question

Calling a bisection method root finiding function and calingit to solve any function in python

I have written a general bisection method to find roots of the provided function, I want to call it to solve a quadratic function. here's my generalroot.py

``````> # determines the root of any general function
>
>
>     tolerance = 1.0e-6
>     def root_bisection (f, a, b, tolerance =1.0e-6):
>       dx = abs(b-a)
>       while dx > tolerance:
>           x = (a+b)/2.0
>           if (f(a)*f(x)) < 0:
>               b = x
>
>           else:
>               a = x
>           dx = abs (b-a)
>       return x
``````

Now I am calling it to solve a quadratic function

``````from math import *
from generalroot import *

def function(y):
y = y**2 + 5*x - 9
return y

func = root_bisection ( y , 0, 1)

print  'Found f(x) =0 at x = %0.8f +/- %0.8f' % ( func , tolerance)
``````

and am getting the following error:

``````raceback (most recent call last):
File "quadfrombisectionroot.py", line 8, in <module>
func = root_bisection ( y , 0, 1)
NameError: name 'y' is not defined
``````

`root_bisection` is expecting a function as its first argument. You should probably call it like that:
``````func = root_bisection(function, 0, 1)
Also you are having a typo in the definition of `function`. Replace `x` with `y`.
As a general piece of advice: Never do `from libraryXYZ import *` but only import the functions you really need. This makes the code much more readable.