#include <iostream>
#include <math.h>
using namespace std;
class FalsePosition
{
public:
FalsePosition()
{
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 FalsePosition::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 FalsePosition::askBrackets()
{
cout << "Enter two points: ";
cin >> x1 >> x2;
}
double FalsePosition::f(double x)
{
return a*x*x+b*x+c; // solves all equation of the form a*x*x+b*x+c;
}
void FalsePosition::findError()
{
Error = fabs((x2-x1) / x2);
}
void FalsePosition::findX0()
{
x0 = x1 - (( f(x1) * (x2 - x1)) / ( f(x2) - f(x1)) );
}
void FalsePosition::solve()
{
int i = 0;
if(f(x1) * f(x2) < 0)
{
cout << "\nS.N.\tx1\tx2\tf(x1)\tf(x2)\tx0\tf(x0)\tError\n";
while(i<=7) // In fixed point set the precision low
{
findX0();
findError();
display();
if(f(x1) * f(x0) < 0)
x2 = x0;
else
x1 = x0;
i++;
}
cout << endl << endl << "The Root is : " << x0 << endl;
}
else
cout << "There lies no root in between the given points" << endl;
}
void FalsePosition::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()
{
FalsePosition b1;
b1.askFun();
b1.askBrackets();
b1.solve();
return 0;
}
C and C++ programs, games, softwares. Easy programming guide. Learn to code and enjoy coding in CoderNepal
Home » False Position
False Position
This is the C++ Program source code for finding the root using False Position Method
Subscribe to:
Comments (Atom)
No comments:
Post a Comment