Newton Raphson Method in C++
Newton Raphson Method in C++
cout<<n<<setw(10)<<a1<<setw(15)<<f(a)<<setw(15)<<g(a)<<setw(15)<<a<<endl;
a1=a-(f(a)/g(a));
n++;
}while((fabs(a-a1))>tol);
cout<<"\n\tThe root is : "<<a1;
return 0;
}
RESULT:
Enter the guess values -
a : 7.25
Enter the desired accuracy : 0.0001
Sl.no x0 f(x0) f'(x0) Root
0 7.25 64.0625 16.5 7.25
1 3.36742 15.0744 8.73485 3.36742
2 1.64165 2.9783 5.2833 1.64165
3 1.07793 0.317781 4.15585 1.07793
4 1.00146 0.00584722 4.00292 1.00146
5 1 1.90735e-006 4 1
The root is : 1
--------------------------------
Process exited after 16.56 seconds with return value 0
Press any key to continue . . .
b) For multiple roots at a time on a given interval :
PROGRAM:
#include<iostream>
#include<math.h>
#define f(x)(x*x+2*x-3)
#define g(x)(2*x+2)
using namespace std;
int main()
{
float a,a1,i,tol;
cout<<"Enter the desired accuracy : ";cin>>tol;
for(i=-10;i<=10;i+=0.1)
{a=i;
a1=i+0.1;
if (f(a)*f(a1)>0) continue;
if (f(a)*f(a1)<0)
do{
a=a1;
a1=a-(f(a)/g(a));
}
while(fabs(a-a1)>=tol);
cout<<"\nThe root is :"<<a1;
}
return 0;
}
RESULT:
Enter the desired accuracy : 0.0001
The root is :-3
The root is :1
--------------------------------
Process exited after 3.493 seconds with return value 0
Press any key to continue . . .