Menu Close

Muller’s Method C++

#include<iostream>
#include<iomanip>
#include<cmath>

using namespace std;
#define I 2

float y(float x)
{
return cos(x)-x*exp(x);
}

int main()
{
int i,itr,maxitr;
float x[4],li,di,mu,s,l,aerr;

cout<<"Enter the initial";
cout<<" approximations";
cout<<endl;

for(i=I-2;i<3;i++)
cin>>x[i];

cout<<"Enter allowed error,";
cout<<" maximum iterations";
cout<<endl;
cin>>aerr>>maxitr;
cout<<fixed;

for(itr=1;itr<=maxitr;itr++)
{
li=(x[I]-x[I-1])/(x[I-1]-x[I-2]);
di=(x[I]-x[I-2])/(x[I-1]-x[I-2]);
mu=y(x[I-2])*li*li-y(x[I-1])*di*di+y(x[I])*(di+li);
s=sqrt((mu*mu-4*y(x[I])*di*li*(y(x[I-2])*li-y(x[I-1])*di+y(x[I]))));

if(mu<0)
l=(2*y(x[I])*di)/(-mu+s);
else
l=(2*y(x[I])*di)/(-mu-s);

x[I+1]=x[I]+1*(x[I]-x[I-1]);

cout<<"Iteration no. ";
cout<<setw(3);
cout<<itr;
cout<<"X=";
cout<<setw(7);
cout<<setprecision(5);
cout<<x[I+1];
cout<<endl;

if(fabs(x[I+1]-x[I])<aerr)
{
cout<<"After ";
cout<<setw(3);
cout<<itr;
cout<<" iterations, the solution is";
cout<<setw(6);
cout<<setprecision(4);
cout<<x[I+1];
cout<<endl;
return 0;
}
for(i=I-2;i<3;i++)
x[i]=x[i+1];
}

cout<<"Iterations not sufficient,";
cout<<" Solution does not converge";
cout<<endl;
return 1;
}

Output

Enter the initial approximations
-1 0 1
Enter allowed error, maximum iterations
0.01 5
Iteration no. 1X=2.00000
Iteration no. 2X=3.00000

More Related Stuff