Pages

Saturday 31 March 2018

Newton Raphson Method in C/C++

PROGRAM :

/*To write a C/C++ program to find roots of an equation using 
Newton Raphson method.*/

#include<iostream>
#include<cmath>
using namespace std;
float a,b,err,x1,x2,x0;
int maxitr,i=1,flag=0;
float f(float x){
return x*log10(x)-1.2;}
float df(float x){
return log10(x)+0.43429;}
int main(){
cout<<"Enter value of a and b :";
cin>>a>>b;
if(f(a)*f(b)>0)
cout<<"No Root or Even Root";
else{
cout<<"Enter maximum iteration and allowed error :";
cin>>maxitr>>err;
x0=(a+b)/2;
while(maxitr>0){
x1=x0;
x2=x1-(f(x1)/df(x1));
cout<<"After "<<i<<" iteration value of x ="<<x2<<"\n";
if(fabs(x1-x2)<err){
cout<<"After "<<i<<" iteration value of x is"<<x2<<"\n";
flag=1;
break;
}
x0=x2;
i++;
maxitr--;
}
if(flag==0)
cout<<"maximum iteration is insufficient";}
return 0;

}


OUTPUT :

Enter value of a and b :5 1
Enter maximum iteration and allowed error :25
0.0001
After 1 iteration value of x = 2.74615
After 2 iteration value of x = 2.74065
After 3 iteration value of x = 2.74065

After 3 iteration value of x is 2.74065