7-18二分法求多项式单根 (20 分)
二分法求函数根的原理为:如果连续函数f(x)在区间[a,b]的两个端点取值异号,即f(a)f(b)<0,则它在这个区间内至少存在1个根r,即f®=0。
二分法的步骤为:
检查区间长度,如果小于给定阈值,则停止,输出区间中点(a+b)/2;否则
如果f(a)f(b)<0,则计算中点的值f((a+b)/2);
如果f((a+b)/2)正好为0,则(a+b)/2就是要求的根;否则
如果f((a+b)/2)与f(a)同号,则说明根在区间[(a+b)/2,b],令a=(a+b)/2,重复循环;
如果f((a+b)/2)与f(b)同号,则说明根在区间[a,(a+b)/2],令b=(a+b)/2,重复循环。
本题目要求编写程序,计算给定3阶多项式 f ( x ) = a 3 x 3 + a 2 x 2 + a 1 x + a 0 f(x)=a3x^3+a2x^2+a1x+a0 f(x)=a3x3+a2x2+a1x+a0
在给定区间[a,b]内的根。
输入在第1行中顺序给出多项式的4个系数a3、a2、a1、a0,在第2行中顺序给出区间端点a和b。题目保证多项式在给定区间内存在唯一单根。
在一行中输出该多项式在该区间内的根,精确到小数点后2位。
//bisection
# include
# include
//calculate the value of f(x)
double polyval (double a, double b, double c, double d, double x);
int main ()
{
double a1, a2, a3, a4, x1, x2, x, eps=0.01;
//input arguments
scanf("%lf %lf %lf %lf", &a1, &a2, &a3, &a4);
scanf("%lf %lf",&x1, &x2);
x = (x1 + x2)/2;
while ((x2 - x1) >= eps)
{
if (polyval(a1, a2, a3, a4, x1) * polyval(a1, a2, a3, a4, x) > 0)
{
x1 = x;
x = (x1 + x2)/2;
}
else if (polyval(a1, a2, a3, a4, x1) * polyval(a1, a2, a3, a4, x) == 0)
{
break;
}
else
{
x2 = x;
x = (x1 + x2)/2;
}
}
printf("%.2lf", x);
return 0;
}
double polyval(double a, double b, double c, double d, double x)
{
double val;
val = a * pow(x,3) + b * pow(x,2) + c * pow(x,1) + d;
return val;
}
if-else循环不能省略f(x)*f(x1)==0的情况,不然当区间中点正好是解的时候就会导致很大偏差。