bisection finding root

Hi every one. I write a code for bisection finding root but it do not work correctly. what's wrong?

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445`` `````` #include #include using namespace std; double Func(double x) { return pow(2, x) + x + 1; } double Bisection_FR(double a, double b) { int n = 0; double x = 0.0; while (b-a>0.01){ double x = (a + b) / 2; if (Func(a)*Func(b) == 0.0) cout << "wrong point" << endl; if (Func(x) == 0.0) cout <<"x is root ---> "<< x << endl; if (Func(x)*Func(a) < 0.0) b = x; else a = x; cout << n++ << endl; } return x; } int main() { double a = 0; double b = 1; cout <<"value of root is :" << Bisection_FR(a, b) << endl; system("pause"); return 0; }``````
Well, you want to remove the "double" on line 16, or you will have two variables called x and you will cout the wrong one. You need one that is in scope from outside the loop.

Lines 18 and 19 aren't doing anything useful. You need a and b such that Func(a) * Func(b) <= 0; i.e. span the root.

You are returning the function 2x + x + 1 on line 7; are you sure that's what you want? It's invariably positive in the interval [0,1]. If you meant the function x2+x+1 instead, well ... that doesn't have any real roots at all.

Last edited on
@lastchance I wanna to have a=x or b=x , then with new value for a or b calculate x again then check conditions and again repeat this to end.
I made a mistake in line 7. I will do relocation of x and 2.
About lines 18 and 19 let them be.
 @lastchance I wanna to have a=x or b=x , then with new value for a or b calculate x again then check conditions and again repeat this to end.

That's fine, but you need to start with F(a) and F(b) having opposite signs (i.e. their product less than or equal to 0 - which they don't).

 I made a mistake in line 7. I will do relocation of x and 2.

That way you will create a function that doesn't have any real roots at all.

 About lines 18 and 19 let them be.

Well, your choice. It just happens to be wrong.
You right. F(a)*F(b) have not value less than zero.
About line 7 i must change my function.
thanks to you.