The principle of finding the function root by the dichotomy is: if the continuous function f (x) takes different signs at the two endpoints of the interval [a, b], ie f (a) f (b) <0, then it is within this interval There is at least one root r, that is f (r) = 0.
The steps of the dichotomy are:
Check the length of the interval, if it is less than the given threshold, stop, output the midpoint of the interval (a + b) / 2; otherwise
if f (a) f (b) <0, calculate the value of the midpoint f ((a + b ) / 2);
if f ((a + b) / 2) is exactly 0, then (a + b) / 2 is the required root; otherwise
if f ((a + b) / 2) and f (a) The same sign means that the root is in the interval [(a + b) / 2, b], let a = (a + b) / 2, repeat the cycle;
if f ((a + b) / 2) and f (b) The same sign means that the root is in the interval [a, (a + b) / 2], let b = (a + b) / 2 and repeat the cycle.
This topic requires writing a program to calculate the root of a given 3rd order polynomial f (x) = a 3 x 3 + a 2 x 2 + a 1 x + a 0 within a given interval [a, b].
Input format:
Enter the four coefficients a 3 , a 2 , a 1 , and a 0 that sequentially give the polynomial in the first row, and give the interval endpoints a and b in the second row. The problem is to ensure that the polynomial has a single root in a given interval.
Output format:
output the root of the polynomial in the interval in one line, accurate to 2 decimal places.
Sample input:
3 -1 -3 1
-0.5 0.5
Sample output:
0.33
Without further ado, go to the code first
#define _CRT_SECURE_NO_DEPRECATE 0
#include<stdio.h>
#include<stdlib.h>
double a0, a1, a2, a3;
double target(double n){
double f;
f = a3*(n*n*n) + a2*(n*n) + a1*n + a0; //计算函数值
return f;
}
int main(){
double a, b;
int i = 0;
scanf("%lf %lf %lf %lf", &a3, &a2, &a1, &a0);
scanf("%lf %lf", &a, &b);
double f1, f2, n, f;
f1 = target(a);
f2 = target(b);
if (f1*f2 < 0){
n = (a + b) / 2;
f = target(n);
while (1){
i++;
if (f == 0){ //f正好为0,则n就是要求的根
printf("%.2lf", n);
break;
}
if (i == 100){ //当出现求不尽的情况时
printf("%.2lf", n);
break;
}
else if (f*f1 < 0){ //如果f与f1异号,则说明根在区间[a,n],令b=n,重复循环
b = n;
n = (n + a) / 2;
}
else if (f*f2 < 0){ //如果f与f2异号,则说明根在区间[n,b],令a=n,重复循环
a = n;
n = (n + b) / 2;
}
f = target(n);
}
}
else if (f1 == 0){ //区间端点是根的情况
printf("%.2lf", a);
}
else if (f2 == 0){ //区间端点是根的情况
printf("%.2lf", b);
}
system("pause");
return 0;
}