Problem 2 Polynomial Root Calculation Problem Description En
Problem 2: Polynomial Root Calculation Problem Description:
Engineers often need to calculate the roots to a given polynomial. For low order polynomials these computations can be done by hand. For higher order polynomials these calculations can be cumbersome, if not impossible, without a computer. One method of finding real roots of a polynomial is the Newton-Raphson algorithm.
In this homework we will write a program that uses the Newton-Raphson method for calculating the roots of a polynomial. Although our program will not be able to solve for complex roots, it will be able to calculate real roots; maybe later we will upgrade the routine to include complex roots. Since it is possible that the polynomial roots are all complex, i.e. no real roots at all, or it may be that the Newton-Raphson routine fails to converge.
(a) Newton-Raphson Algorithm:
Write a C program that prompts the user to input a set of 5th-order polynomial coefficients, of the form c5; c4; c3; c2; c1; c0. Also, the user will need to submit an initial value of x which serves as the starting condition of the Newton-Raphson algorithm.
The 5th-order polynomial has the form
y = c5 x5 + c4 x 4 + c3 x 3 + c2 x 2 + c1 x + c0
We know that the first derivative of y with respect to x is
5 c5 x 4 + 4 c4 x 3 + 3 c3 x 2 + 2 c2 x + c1
We can use this information to find the roots of the polynomial. The basic idea, in the Newton-Raphson method, is as follows:
(a) Given an initial guess (or the updated value) x, and polynomial coefficients c,
calculate y
(b) Check to see if y is close enough to zero, i.e. within some small tolerance close to zero.
(i) If so then terminate. Algorithm has converged! (ii) If not then continue
(c) Use the current value of x to calculate
(d) Create a new guess for x using the update formulate x = x
Solution
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int maxpow,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(\"\ NEWTON RAPHSON METHOD\");
printf(\"\ ENTER THE MAXIMUM POWER OF X = \");
scanf(\"%d\",&maxpow);
for(i=0;i<=maxpow;i++)
{
printf(\"\ x^%d = \",i);
scanf(\"%d\",&coef[i]);
}
printf(\"\ \");
printf(\"\ Your polynomial is = \");
for(i=maxpow;i>=0;i--)
{
printf(\" %dx^%d\",coef[i],i);
}
printf(\"\ First approximation x1 ----> \");
scanf(\"%f\",&x1);
printf(\"\ \ ---------------------------------------\ \");
printf(\"\ Iteration \\t x1 \\t F(x1) \\t \\tF\'(x1) \");
printf(\"\ ------------------------------------------\ \");
do
{
cnt++;
fx1=fdx1=0;
for(i=maxpow;i>=1;i--)
{
fx1+=coef[i] * (pow(x1,i)) ;
}
fx1+=coef[0];
for(i=maxpow;i>=0;i--)
{
fdx1+=coef[i]* (i*pow(x1,(i-1)));
}
t=x2;
x2=(x1-(fx1/fdx1));
x1=x2;
printf(\"\ \\t %d \\t%.3f \\t %.3f\\t\\t%.3f \",cnt,x2,fx1,fdx1);
}while((fabs(t - x1))>=0.0001);
printf(\"\ THE ROOT OF EQUATION IS = %f\",x2);
getch();
}