Bisection procedure for [f(x) = x² -2] (sqrt2)

98 Views Asked by At

I'm trying to write a program that calculates the root of f(x) = x^2 -2, but it does not seem to change the values of x, fa, and fb.

  int x2(float a, float b)
    {
        float tmp = (a + b) / 2; 
        return tmp; 
    }
    
    int func(float a)
    {
        float tmp = (a * a) - 2;
        return tmp;
    } 
    
    int main()
    {
        float a = 1, b = 2;
        float fa = func(a), fb = func(b);
        float y = 0, x=0; 
    
        while (fa < 0 && fb > 0)
        {
    
            y = x2(a,b);
            x = func(y);
    
            if (x < 0) { a = x2(a, b); b = b; }
            if (x > 0) { a = a; b = x2(a, b); }
            if (x == 0) { cout << "Zero-Point: " << x << endl; break; }
    
            fa = func(a), fb = func(b);
        }
    }
1

There are 1 best solutions below

0
Zeta On

All your functions return int, but func and x2 should return float. Otherwise you will end up with x2 returning 1 on x2(1, 2) and thus a = y = 1 permanently.