Search code examples
c++divide-and-conquer

Incorrect Output when applying Divide & Conquer


I have to solve an one-root equation in an interval, using Divide & Couquer. Here is my code:

#include<bits/stdc++.h>

double coef[4];
int d=3;

double f(double x){
    int i;
    double res;
    for(i=0;i<=d;i++) res+=coef[i]*pow(x,i);
    return res;
}

double solve(double left,double right){
    double mid=(left+right)/2;

    if(abs(f(mid))<=1e-8) return mid;
    if(right-left<=1e-4) return mid;

    printf("%.4f %.4f %.4f\n",left,mid,right);

    if(f(mid)*f(left)>=0) return solve(mid,right); 
    if(f(mid)*f(right)>=0) return solve(left,mid);
}

int main(){

    coef[0]=-10;
    coef[1]=0;
    coef[2]=0;
    coef[3]=1.5;

    printf("%lf\n",solve(-10,10));
}

Then I use it to solve 1.5x^3-10=0 with two bound -10 and 10, but it seems to me that if(f(mid)*f(right)>=0) return solve(left,mid); doesn't work at all.

-10.0000 0.0000 10.0000
0.0000 5.0000 10.0000
5.0000 7.5000 10.0000
7.5000 8.7500 10.0000
8.7500 9.3750 10.0000
9.3750 9.6875 10.0000
9.6875 9.8438 10.0000
9.8438 9.9219 10.0000
9.9219 9.9609 10.0000
9.9609 9.9805 10.0000
...

I know that the root of the equation is 1.8821 so the output is incorrect.

The same happens with [-20, 20].

If I test with [-1.000.000, 1.000.000] the output gives me the root 500000.0000 which is clearly incorrect.

So what's wrong with my function solve()?

Any help will be highly appreciated!


Solution

  • In your code, res is not initialized in f which sould be initialized as zero.

    In addition, abs should be replaced by std::fabs or std::abs if you don't type using namespace std;.

    Fixing these two points, it will work fine.

    DEMO is here.