All Programs are Written and Compiled in Dev C++. So, it may generate some error in case of other compilers and may need some modifications in program. Download Dev C++

Friday 13 February 2015

Newton-Raphson's Method

#include<iostream>
#include<math.h>
#include<iomanip>
#define err 0.0001
//Correction upto three places
using namespace std;
float f(float x)
{
return pow(x,4)-x-9;
//Function f(x)
}
float df(float x)
{
return 4*pow(x,3)-1;
//Diffirenciation of f(x)
}

int main()
{
int i=1,max;
float x0,x1,h;
cout<<"Enter initial approximate roots x0 : ";
cin>>x0;
cout<<"Enter max No of iterations: ";
cin>>max;
cout<<setprecision(6)<<"Iterations\tRoot\n";
while(i<max)
{
h=f(x0)/df(x0);
x1=x0-h;
cout<<i<<"\t\t"<<x1<<endl;
i++;
if(fabs(h)<err)
{
cout<<"\nRoot after "<<i<<" iterations="<<setprecision(5)<<x1<<endl;
return 0;
}
x0=x1;
}
cout<<"\nSolution Does not cover: "<<i<<" iteration not sufficient";

return 1;
}

No comments:

Post a Comment