pta 7-41 二分法求多项式单根 (20分)

#include <algorithm>
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <cmath>
#include <cstring>
#include <deque>
#include <queue>
#include <cmath>

using namespace std;

#define ios                    \
  ios::sync_with_stdio(false); \
  cin.tie(0);                  \
  cout.tie(0)
#define ll long long
#define met(a,b) memset(a,b,sizeof(a))

double a3,a2,a1,a0,a,b,res,temp;;

double f(double x){
	return a3*pow(x,3)+a2*pow(x,2)+a1*x+a0;
}
int main(){
    cin>>a3>>a2>>a1>>a0>>a>>b;
    while(1){
        if(b-a<0.01){
            printf("%.2lf",(a+b)/2);
			return 0;
        }
		if(f((a+b)/2)==0){
			res=(a+b)/2;
			printf("%.2lf",res);
			return 0;
		}
		if(f(a)==0){
			printf("%.2lf",a);
			return 0;
		}
		if(f(b)==0){
			printf("%.2lf",b);
			return 0;
		}
		if(f(a)*f((a+b)/2)>=0){
			a=(a+b)/2;
		}
		else{
			b=(a+b)/2;
		}
    }
    ios;
    return 0;
}

二分法求函数根的原理为:如果连续函数f(x)在区间[a,b]的两个端点取值异号,即f(a)f(b)<0,则它在这个区间内至少存在1个根r,即f(r)=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​​在给定区间[a,b]内的根。

输入格式:

输入在第1行中顺序给出多项式的4个系数a​3​​、a​2​​、a​1​​、a​0​​,在第2行中顺序给出区间端点a和b。题目保证多项式在给定区间内存在唯一单根。

输出格式:

在一行中输出该多项式在该区间内的根,精确到小数点后2位。

输入样例:

3 -1 -3 1
-0.5 0.5

输出样例:

0.33
发布了32 篇原创文章 · 获赞 7 · 访问量 825

猜你喜欢

转载自blog.csdn.net/Young_Naive/article/details/104027630