二分法求多项式单根

二分法求多项式单根_第1张图片
二分法求多项式单根_第2张图片

输出格式:

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

输入样例:

3 -1 -3 1
-0.5 0.5

输出样例:

0.33

idea

  • 精确到小数点后两位
    =>阈值为0.001

solution1

#include 
#include 
double f(double a[], double x);
int main(){
	double arr[4], a, b;
	for(int i = 0; i < 4; i++)
		scanf("%lf", arr + i);
	scanf("%lf%lf", &a, &b);
	while(b - a > 0.001 && f(arr, b)*f(arr, a) <= 0){
		if(f(arr, b) == 0){
			printf("%.2f", b);
			return 0;
		}
		else if(f(arr, a) == 0){
			printf("%.2f", a);
			return 0;
		}
		else{
			double mid = (a + b) / 2;
			if(f(arr, a)*f(arr, mid) < 0) b = mid;
			else a = mid;
		}
	}
	printf("%.2f", (a + b) / 2);
	return 0;
}

double f(double a[], double x){
	double ans = 0, power = 1;
	for(int i = 3; i >= 0; i--){
		ans += a[i]*power;
		power *= x;
	}
	return ans;
}

solution2

#include 
#include 
double f(double a[], double x);
int main(){
	double arr[4], a, b, mid;
	for(int i = 0; i < 4; i++)
		scanf("%lf", arr + i);
	scanf("%lf%lf", &a, &b);
	while(b - a > 0.001){
		mid = (a + b) / 2;
		if(f(arr, mid) == 0) break;
		else if(f(arr, a)*f(arr, mid) < 0) b = mid;
		else a = mid;
	}
	printf("%.2f", (a + b) / 2);
	return 0;
}

double f(double a[], double x){
	double ans = 0, power = 1;
	for(int i = 3; i >= 0; i--){
		ans += a[i]*power;
		power *= x;
	}
	return ans;
}

solution3

#include 
double f(double a[], double x);
int main(){
	double arr[4], a, b, mid;
	for(int i = 0; i < 4; i++)
		scanf("%lf", arr + i);
	scanf("%lf%lf", &a, &b);
	while(b - a > 0.001){
		mid = (a + b) / 2;
		if(f(arr, mid) == 0) break;
		else if(f(arr, a)*f(arr, mid) < 0) b = mid;
		else a = mid;
	}
	printf("%.2f", (a + b) / 2);
	return 0;
}

double f(double a[], double x){
	return a[0]*x*x*x + a[1]*x*x + a[2]*x + a[3];
}

你可能感兴趣的:(算法,算法,数据结构)