Search This Blog

Tuesday 2 February 2016

Finding Roots of Algebraic Equation using Bisection Method

#include<iostream>
#include<math.h>

using namespace std;

class Equation
{
int a[20],n;
double x,y,root,m;
public:
Equation();
void roots();
double solution(double t);
};

Equation::Equation()
{
cout << "\t\tEnter highest power of equation: ";
cin >> n;
cout << endl;
for(int i=n;i>=0;i--)
{
cout << "\t\tEnter coefficient of x^" << i << ":";
cin >> a[i];
cout << endl;
}
cout << "\t\tEnter interval for roots:";
cin >> x >> y;
cout << endl;
}

void Equation::roots()
{
if((solution(x)*solution(y))>0)
cout << "Roots does not exist in given interval (" << x << "," << y << ")" << endl;
else
{
if((y-x)<=0.00001)
cout << "Root is " << x << endl;
else
{
m=(x+y)/2;
if((solution(x)*solution(m))<0)
{
y=(x+y)/2;
roots();
}
else
{
x=(x+y)/2;
roots();
}
}
}
}

double Equation::solution(double t)
{
double x=0;
for(int i=0;i<=n;i++)
{
x=x+(a[i]*pow(t,i));
}
return x;
}

int main()
{
Equation a;
a.roots();
return 0;
}

No comments:

Post a Comment