Portal
7-18 Dichotomy to find a single root of a polynomial : Category: floating-point
dichotomy to find the root of a function: If the continuous function f(x) takes different signs at the two end points of the interval [a, b], that is f(a)f(b)<0, then it has at least one root r in this interval, that is, f(r)=0.
The steps of the dichotomy are:
Check the interval length, if it is less than the given threshold, stop and output the midpoint of the interval (a+b)/2; otherwise,
if f(a)f(b)<0, calculate the midpoint value 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) With the same sign, it 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) With the same sign, it means that the root is in the interval [a, (a+b)/2], let b=(a+b)/2, repeat the cycle.
Input sample:
3 -1 -3 1
-0.5 0.5
Sample output:
0.33
code show as below
#include<iostream>
using namespace std;
double a1,a2,a3,a0;
double f(double x)
{
return a3*x*x*x
+a2*x*x
+a1*x
+a0;
}
int main()
{
scanf("%lf%lf%lf%lf",&a3,&a2,&a1,&a0);
double l,r,mid;
scanf("%lf%lf",&l,&r);
while(r-l>=1e-4)
{
mid=(l+r)/2;
if(f(mid)/f(l)>=0)l=mid;
else r=mid;
}
printf("%.2lf",l);
}