Menu Close

Newton Raphson Method C++

#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;

float f(float x)
{
return x*log10(x)-1.2;
}

float df(float x)
{
return log10(x)+0.43429;
}

int main()
{
int itr, maxitr;
float h, x0, x1, aerr;

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

for(itr=1;itr<=maxitr;itr++)
{
h=f(x0)/df(x0);
x1=x0-h;
cout<<"Iteration no. "<<setw(3)<<itr;
cout<<"X="<<setw(9)<<setprecision(6);
cout<<x1<<endl;

if(fabs(h)<aerr)
{
cout<<"After no. "<<setw(3)<<itr;
cout<<" Iteration, root=";
cout<<setw(8)<<setprecision(6)<<x1;
return 0;
}

x0=x1;
}

cout<<"Iteration not sufficient, ";
cout<<"solution does not converge"<<endl;
return 1;
}

Output

Enter x0, allowed error, maximum iterations
2 0.000001 10
Iteration no. 1X= 2.813170
Iteration no. 2X= 2.741109
Iteration no. 3X= 2.740646
Iteration no. 4X= 2.740646
After no. 4 Iteration, root=2.740646

More Related Stuff