C中的此代碼(附在帖子後)使用Newton - Raphson method來查找特定區間中多項式的根。牛頓方法程序(在C中)無限循環運行
此代碼適用於x^3 + x^2 + x + 1
等多項式,但對於x^3 - 6*x^2 + 11*x - 6
等一些多項式,運行時間會變得無限。這就是說,對於在輸入的時間間隔內具有一個或零個根的多項式,該代碼工作正常,但如果存在多於一個根,則它無限期地運行。
如果有人找到解決方案,請讓我知道。我在代碼中寫了評論來指導讀者,但如果有人發現很難理解,可以在評論中提問,我會解釋它。
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>
int check(float num) //just a function to check for the correct input
{
char c;
scanf("%c",&c);
if(isalpha((int)c))
printf("you entered an alphabet\n");
else
printf("you entered a character, please retry\n");
return 0;
}
float func(float *p,int order,double x) //calculates the value of the function required in the formmula in main
{
double fc=0.0;
int i;
for(i=0;i<=order;i++)
{
fc=fc+(double)(*p)*pow(x,(double)i);
p++;
}
return fc;
}
float derv(float *q,int order,double x) //calculates the derivative of the function required in the formmula in main
{
double dv=0.0,i;
for(i=1;i<=order;i++)
{
dv=dv+(double)(*q)*(pow(x,(double)(i-1)))*(double)i;
q++;
}
return dv;
}
int main()
{
float coeff[1000];
int order,count=0,i,j=0;
char ch;
float a,b;
double val[5];
printf("roots of polynomial using newton and bisection method\n");
printf("enter the order of the equation\n");
while(scanf("%d",&order)!=1)
{
printf("invalid input.please retry\n");
while(getchar()!='\n'){}
}
printf("enter the cofficients\n");
for(i=0;i<=order;i++)
{
printf("for x^%d :",order-i);
printf("\n");
while(scanf("%f",&coeff[i])!=1)
{
check(coeff[i]);
}
}
while(getchar()!='\n'){} //this clears the buffer accumulated upto pressing enter
printf("the polynomial you entered is :\n");
for(i=0;i<=order;i++)
{
printf(" %fx^%d ",coeff[i],order-i);
}
printf("\n");
//while(getchar()!='\n'){};
/* fflush(stdout);
fflush(stdin);*/
printf("plese enter the interval domain [a,b]\n");
printf("enter a and b:\n");
scanf("%f %f",&a,&b);
while(getchar()!='\n'){}
printf("the entered interval is [%f,%f]",a,b);
fflush(stdout);
fflush(stdin);
//this array is used to choose a different value of x to apply newton's formula recurcively in an interval to scan it roperly for 3 roots
val[0]=(double)b;
val[1]=(double)a;
val[2]=(double)((a+b)/2);
double t,x=val[0],x1=0.0,roots[10];
while(1)
{
t=x1;
x1=(x-(func(&coeff[0],order,x)/derv(&coeff[0],order,x))); //this is the newton's formula
x=x1;
if((fabs(t - x1))<=0.0001 && count!=0)
{
roots[j]=x;
j++;
x=val[j]; // every time a root is encountered this stores the root in roots array and runs the loop again with different value of x to find other roots
t=0.0;
x1=0.0;
count=(-1);
if(j==3)
break;
}
count++;
}
printf("the roots are = \n");
int p=0;
for(j=0;j<3;j++)
{
if(j==0 && roots[j]>=a && roots[j]<=b)
{
printf(" %f ",roots[j]);
p++;
}
if(fabs(roots[j]-roots[j-1])>0.5 && j!=0 && roots[j]>=a && roots[j]<=b)
{
printf(" %f ",roots[j]);
p++;
}
}
if(p==0)
printf("Sorry,no roots are there in this interval \n");
return 0;
}
上[牛頓法(維基百科的文章https://en.wikipedia.org/wiki/Newton %27s_method)概述了它無法收斂的原因。據推測,你遇到了其中一些原因。 –