/*Newton Rapsons method : for solving non linear equations*/
#include<iostream.h>
#include<conio.h>
#include<math.h>
double funct(double);
double derv(double);
int main()
{
double x0,x1,temp;
int n=0,flag=0;
clrscr();
cout<<"X0\n";
cin>>x0;
do{
if(fabs(derv(x0))<0.00001)
{
cout<<"Error: divide overflow !!";
flag=1;
break;
}
temp=x0;
x1=x0-funct(x0)/derv(x0);
n++;
if(n>200)
{
cout<<"Error: Exccess overlooping !!";
flag=1;
break;
}
x0=x1;
}while(fabs(funct(x0))>0.00001);
if(flag==0)
{
cout<<"c: "<<x0;
cout<<"\nf(c):"<<funct(x0)<<"\nn: "<<n<<"\nerror: "<<(x0-temp)/ x0;
}
getch();
return 0;
}
//function and its derivative
double funct(double x)
{
// return x*exp(x)-1;
return x*x+log(x)-5;
// return pow(x,3)-x-3;
//return pow(x,4)-79.08*pow(x,3)-21.392*x*x-1581.6*x-827.84;
}
double derv(double x)
{
// return exp(x)*(1+x);
return 2*x+1/x;
// return 3*x*x-1;
//return 4*pow(x,3)-3*79.08*pow(x,2)-2*21.392*x-1581.6;
}
C C++ Code : Newton rapshon's method for solving non-linear equation
Subscribe to:
Post Comments
(
Atom
)
thanks!
ReplyDeleteYou are welcome.
DeleteOutput
ReplyDelete