C program of Newton Raphson Method : Newton Raphson method is a method of approximating a root of the polynomial equation also called the method of tangents. In Newton’s method, the initial (“first”) approximation x = a1 is used to find a second, more accurate, approximation by drawing the tangent to the graph of y = f(x) at the point A[a1, f(a1)] up to the intersection of the tangent with the x-axis. The point of intersection is
x = a1 – f(a1)/f’(a1)
and is adopted as the new value a2 of the root. By repeating this process as necessary, we can obtain increasingly accurate approximations a2, a3, … of the root provided that the derivative f’(x) is monotonic and preserves its sign on the segment containing root.
How to use the C program :
Consider an example : f(x) = x^2 - 4 as our polynomial equation. We want to calculate its root and say first approximation =6. Then maximum power of X = 2, coefficients of x^0 = -4, x^1 = 0, x^2 = 1 & first approximation =6. Now C program of Newton Raphson Method will display the iterations and root of the polynomial as output.
C program of Newton Raphson Method :
#include<conio.h> #include<stdio.h> #include<stdlib.h> #include<math.h> int max_power,i=0,cnt=0,flag=0; int coef[10]={0}; float x1=0,x2=0,t=0; float fx1=0,fdx1=0; int main() { printf("-----------------------------------------------------------\n"); printf("----------------------Made by C code champ-----------------\n"); printf("-----------------------------------------------------------\n\n"); printf("\n\n\t C PROGRAM FOR NEWTON RAPHSON METHOD"); printf("\n\n\n\tENTER THE MAXIMUM POWER OF X = "); scanf("%d",&max_power); for(i=0;i<=max_power;i++) { printf("\n\t x^%d = ",i); scanf("%d",&coef[i]); } printf("\n"); printf("\n\tTHE POLYNOMIAL IS = "); for(i=max_power;i>=0;i--)/*printing coefficients*/ { printf(" %dx^%d",coef[i],i); } printf("\n\n\tFirst approximation x1 ----> "); scanf("%f",&x1); printf("\n\n-----------------------------------------------------------\n"); printf("\n ITERATION \t x1 \t F(x1) \t \tF'(x1) "); printf("\n-----------------------------------------------------------\n"); do { cnt++; fx1=fdx1=0; for(i=max_power;i>=1;i--) { fx1+=coef[i] * (pow(x1,i)) ; } fx1+=coef[0]; for(i=max_power;i>=0;i--) { fdx1+=coef[i]* (i*pow(x1,(i-1))); } t=x2; x2=(x1-(fx1/fdx1)); x1=x2; printf("\n\t %d \t%.3f \t %.3f\t\t%.3f ",cnt,x2,fx1,fdx1); }while((fabs(t - x1))>=0.0001); printf("\n\n\n\t THE ROOT OF EQUATION IS = %f",x2); getch(); }
We hope that you all have enjoyed the C program of Newton Raphson Method. If you have any doubts related to the program ask us in form of comments.
The post C program of Newton Raphson Method | C code champ appeared first on C codechamp.