#include <bits/stdc++.h>
#include <iostream>
using namespace std;
double value(double A ,double B,double C,double x)
{
return((A*x*x*x)+B*x+C);
}
int bisection(double A,double B,double C,double a,double b)
{
int c=0;
double xr1;
double xr2=0.0;
xr1=(a+b)/2.0;
cout<<"n\ta\tb\txr\tf(x)\n"<<endl;
do
{
c++;
if(value(A,B,C,a)*(value(A,B,C,xr1))==0)
{
cout<<c<<"\t"<<a<<"\t"<<b<<"\t"<<xr1<<"\t"<<value(A,B,C,xr1)<<endl;
break;
}
else if(value(A,B,C,a)*(value(A,B,C,xr1))<0)
{
cout<<c<<"\t"<<a<<"\t"<<b<<"\t"<<xr1<<"\t"<<value(A,B,C,xr1)<<endl;
b=xr1;
xr2=xr1;
xr1=(a+b)/2.0;
}
else if(value(A,B,C,a)*(value(A,B,C,xr1))>0)
{
cout<<c<<"\t"<<a<<"\t"<<b<<"\t"<<xr1<<"\t"<<value(A,B,C,xr1)<<endl;
a=xr1;
xr2=xr1;
xr1=(a+b)/2.0;
}
}while(fabs(xr1-xr2)>0.0001);
cout<<"Root is="<<xr1<<endl;
cout<<"Total Count="<<c<<endl;
}
int falseP(double A,double B,double C,double a,double b)
{
int c=0;
double xr1;
xr1=(((a*(value(A,B,C,b)))-b*(value(A,B,C,a)))/(value(A,B,C,b)-value(A,B,C,a)));
double xr2=0.0;
cout<<"n\ta\tb\txr\tf(x)\n"<<endl;
do
{
c++;
if(value(A,B,C,a)*(value(A,B,C,xr1))==0)
{
cout<<c<<"\t"<<a<<"\t"<<b<<"\t"<<xr1<<"\t"<<value(A,B,C,xr1)<<endl;
break;
}
else if(value(A,B,C,a)*(value(A,B,C,xr1))<0)
{
cout<<c<<"\t"<<a<<"\t"<<b<<"\t"<<xr1<<"\t"<<value(A,B,C,xr1)<<endl;
b=xr1;
xr2=xr1;
xr1=(((a*(value(A,B,C,b)))-b*(value(A,B,C,a)))/(value(A,B,C,b)-value(A,B,C,a)));
}
else if(value(A,B,C,a)*(value(A,B,C,xr1))>0)
{
cout<<c<<"\t"<<a<<"\t"<<b<<"\t"<<xr1<<"\t"<<value(A,B,C,xr1)<<endl;
a=xr1;
xr2=xr1;
xr1=(((a*(value(A,B,C,b)))-b*(value(A,B,C,a)))/(value(A,B,C,b)-value(A,B,C,a)));
}
}while(fabs(xr1-xr2)>0.0001);
cout<<"Root is="<<xr1<<endl;
cout<<"Total Count="<<c<<endl;
}
int main()
{
double A,B,C;
cout<<"Input Co-efficient of X^3 = ";
cin>>A;
cout<<"Input Co-efficient of X = ";
cin>>B;
cout<<"Input Constant = ";
cin>>C;
double a,b;
for(a=0;a<1000;a++)
{
if(value(A,B,C,a)<0 && value(A,B,C,a+1)>0)
{
break;
}
}
b=a+1;
int s;
cout<<"Enter your choice:\n1. For Bisection Method\n2.False Position Method"<<endl;
while(cin>>s)
{
if(s==1)
{
bisection(A,B,C,a,b);
}
if(s==2)
{
falseP(A,B,C,a,b);
}
if(s==0)
{
break;
}
}
}
0 comments:
Post a Comment