This is the solution for finding the roots of a function by Bisection Method in C++ Object Oriented Approach
#include <iostream>
#include <math.h>
using namespace std;
class Bisection
{
public:
Bisection()
{
Error = 99;
}
void askFun();
void askBrackets();
double f(double x);
void display();
void findError();
void findX0();
void solve();
private:
double a,b,c;
double x0,x1,x2;
double Error;
};
void Bisection::askFun()
{
//can only perform for quadratic eqn. change for other equation
cout.setf(ios::fixed,ios::floatfield);
cout.precision(4);
cout << "Enter a,b,c of ax^2+bx+c = 0: " ;
cin >> a >> b >> c;
}
void Bisection::askBrackets()
{
cout << "Enter two points: ";
cin >> x1 >> x2;
}
double Bisection::f(double x)
{
return a*x*x+b*x+c; // solves all equation of the form a*x*x+b*x+c;
}
void Bisection::findError()
{
Error = fabs((x2-x1) / x2);
}
void Bisection::findX0()
{
x0 = (x1+x2)/2;
}
void Bisection::solve()
{
if(f(x1) * f(x2) < 0)
{
cout << "\nS.N.\tx1\tx2\tf(x1)\tf(x2)\tx0\tf(x0)\tError\n";
while(Error>=0.00009)
{
findX0();
findError();
display();
if(f(x1) * f(x0) < 0)
x2 = x0;
else
x1 = x0;
}
cout << endl << endl << "The Root is : " << x0 << endl;
}
else
cout << "There lies no root in between the given points" << endl;
}
void Bisection::display()
{
static int i;
cout << ++i << "\t" << x1 << "\t" << x2 << "\t" << f(x1) << "\t" << f(x2) << "\t" << x0 <<
"\t" << f(x0) << "\t" << Error << endl;
}
int main()
{
Bisection b1;
b1.askFun();
b1.askBrackets();
b1.solve();
return 0;
}
No comments:
Post a Comment