hey guys:
im having a problem with the bisection method using C++ , the code suppose to find the root of this equation "X cube minus 3X plus 1" on [0,1] after 5 iterations and after doing it manually the answer should be x=0.009368
it keeps giving me 0.25 and even if i raise iteration number the x raises up which is wrong

``````#include <iostream>
#include <math.h>
using namespace std;
int main () {
double a1=0.0;
double b1=0.0;
int N;
double a, b;
double x=0.0;
int i;

cout << "Welcome to the Root Finding Calculator using the Bisection Method!" << endl << endl;
cout << "please enter an endpoint, a: ";
cin >> a;
cout << "please enter the other endpoint, b: ";
cin >> b;
cout << "please enter the maximum number of iterations to be performed: ";
cin >> N;
x=(a+b)/2;
double Fa = pow ((a),3)-(3*a)+1;
double Fx = pow ((x),3)-(3*x)+1;
for (i = 1; i <= N; i++) {
if ((Fa*Fx) == 0 ) {
cout << "The root is " << x << endl;
return 0;
}
x=(a+b)/(2);
if ((Fa * Fx) > 0) {
a1 = x;
b1 = b;
}
else {
a1 = a;
b1 = x;
x=((a1+b1)/2);
}
}
cout <<"Fa ="<<Fa<<"\nFx="<<Fx<<  "\n a = " << a << "\n b = " << b ;
cout<<"\n a1="<<a1<<"\n b1="<<b1<<"\n the root x = "<<x;
return 0;
}``````

thanks in advance ;)

at line 27, u should not write x=(a+b)/2.
it should work fine after this ammendment

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.