Code:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
//this program calculates the one root of an polynomial,in a interval [a,b]
//user enters the coefficients and Degree of polynomial,After program Must calculate
//the root within +10^-6 and -10^-6 tolerance.
float denklem_sonuc(float *cof,float kac,int degreex)//this calculates the the polinomial value.
{ //for example, cof={1,3,3,1} ,kac=-1, degreex=3 ,(1*x^3+3*X^2+3*x^1+1*X^0)
float ax,sqrx; // in the above equation -1 will be assumed as X value. and Will calculate the answer.
float cvpx=0;
int i,i2;
for(i=0;i<(degreex+1);i++)
{
ax=kac;
sqrx=1;
for(i2=0;i2<i;i2++)
{
sqrx=ax*sqrx; //This is power of ax calculation
}
cvpx=cof[degreex-i]*sqrx+cvpx; //this is the total summation of the every X^ * coefficient
}
printf("The Equation=%.20f\n",cvpx); //This displays the equation value when I put 'kac' number in the equation.
return cvpx;
}
int main()
{
int truth=1;
int i;
float b=0,a=0;
int sayac=0;
int degreex;
int z=1;
float sqrx=1,j=0;
float *cof;
float cvp1=0;
printf("Enter polinom degree:");
scanf("%d",°reex);
cof=calloc(degreex,sizeof(double));//if there is 5th degree polynomial,there will be 6 coefficients.
for(i=0;i<(degreex+1);i++) //Calloc creates a pointer array which i can store the coefficients in it.
{
printf("please enter the coefficient of X^%d:",(degreex-i));//coefficients of eq.Stored here
scanf("%f",&cof[i]);
}
//for(i=0;i<(degreex+1);i++) printf("%.20f\n",cof[i]);
printf("The lowest number of interval, a:");
scanf("%f",&a);
printf("The highest number of interval, b:");
scanf("%f",&b);
printf("[%f,%f] Enter any key to calculate the root in this interval\n",a,b);
getch();
while(1) //infinite loop,i put a option if 1000 times after,the answer of equation cant converge to [1-0] break and say "no root."
{
j=b-denklem_sonuc(cof,b,degreex)*((b-a)/(denklem_sonuc(cof,b,degreex)-denklem_sonuc(cof,a,degreex)));
a=b; //this is a method for approximately converges to 0 ,and finds the root with some error.
b=j;
sayac++;
if((denklem_sonuc(cof,j,degreex)<pow(10,-20))&&(denklem_sonuc(cof,j,degreex)>-pow(10,-20))) {
printf("My Root=%.20f\n",j);
printf("The polynomial value while the root used in equation=%.20f\n",denklem_sonuc(cof,j,degreex));
break;
}
if (denklem_sonuc(cof,j,degreex)<1) truth=0;
if ((sayac>1000)&&(truth!=0))
{
printf("No root, in this interval.");
break;
}
}
return 0;
}
The roout should be -1 or +-10^-6 tolerance of -1