asuman_sare
asuman_sare

Reputation: 91

bisection method in C

I wrote a code to find the root of a 4th degree polynom with bisection method. I wrote the same code for 3th polynom,too and that works fine. I just copy and paste, and add 4th degree term and it didn't work fine.Here is my code

double root4(double a0, double a1, double a2, double a3, double a4, double xs, double xe)
{
    /*0.000001 is stop point*/
    double xs_value, xe_value, stop_condition, pos_root, pos_root_val;  /*Here "y" means f(y) and pos means possible*/
    int n = 1,temp;
    do
    {
        xs_value = (a4*(xs*xs*xs*xs)) + (a3*(xs*xs*xs)) + (a2*(xs*xs)) + (a1*xs) + a0;
        xe_value = (a4*(xe*xe*xe*xe)) + (a3*(xe*xe*xe)) + (a2*(xe*xe)) + (a1*xe) + a0;
        stop_condition = (xe-xs)/(pow(2,n));
        pos_root = (xs + xe) / 2;
        pos_root_val =(a4*(pos_root*pos_root*pos_root*pos_root))+(a3*(pos_root*pos_root*pos_root))+(a2*(pos_root*pos_root))+(a1*pos_root)+a0;
        if(xs_value * pos_root_val < 0)
            xe = pos_root;
        if(xe_value * pos_root_val < 0)
            xs = pos_root;      
        n++;
    }
    while(stop_condition >= 0.000001);
    return pos_root;
}

When I give these values

root4(1,10,7,3,-4,-50,50)); last two number means interval like [-50,50]

It gives me

0.000000

And when I change interval as [-50,51] outbut becomes 0.500000 I think problem is about boundaries but as I said, it works fine for 3th degree polynom.

Upvotes: 0

Views: 274

Answers (1)

Yakov Galka
Yakov Galka

Reputation: 72469

Your polynomial looks like this (note that the y-axis is scaled down A LOT):

enter image description here

In particular, the function is negative on both sides of the interval. In order for the bisection method to converge to a root, the function must be positive on one side of the interval and negative on the other. For 3rd degree (or any odd degree) polynomials, this is always the case if you take a big enough interval. For 4th degree (or any even degree) this is exactly the opposite.

The bottom line is that this is not an error in your algorithm. It's just the initial conditions you give it that are bad.

Upvotes: 3

Related Questions