1

I coded a "bisection method" but it run forever, please help me, thanks a lot my code, just a simple to find nearest root of x^3+4*x^2-10, think it will stop in 14 times , but it not(i try a and b as 1 and 2)

 void bis(double a, double b)
{
    cout << fixed << setprecision(8);
    double x = (a + b) / 2;
    double result = pow(x, 3) + 4 * pow(x, 2) - 10;
    int n = 0;
    while (abs(result) > 0,0001) {
        x = (a + b) / 2;
        result = pow(x, 3) + 4 * pow(x, 2) - 10;
        if (pow(a, 3) + 4 * pow(a, 2) - 10 > 0 && pow(b, 3) + 4 * pow(b, 2) - 10 < 0) {
            n++;
            if (result > 0) {
                cout << n << "     " << a << "    " << b << "   " << x << "    " << result << endl;
                a = x;
            } else if (result < 0) {
                cout << n << "     " << a << "    " << b << "   " << x << "    " << result << endl;
                b = x;
            }
        }
        if (pow(a, 3) + 4 * pow(a, 2) - 10 < 0 && pow(b, 3) + 4 * pow(b, 2) - 10 > 0) {
            n++;
            if (result > 0) {
                cout << n << "     " << a << "    " << b << "   " << x << "    " << result << endl;
                b = x;
            } else if (result < 0) {
                cout << n << "     " << a << "    " << b << "   " << x << "    " << result << endl;
                a = x;
            }
        }
    }
}
  • 2
    _`0,0001`_ You probably meant to write a `double` literal: `0.0001`. Otherwise your condition equals to `while (abs(result) > 1)` – πάντα ῥεῖ Oct 27 '18 at 08:56
  • yesssssss, that it, 0.0001 ,it stop run infinity times, thanks, but i still dont understand i use pow(10,-4) it still run infinity? – Quốc Khánh Lê Oct 27 '18 at 08:59
  • 1
    It's because of the comma operator: `abs(result)>0,0001` is understood as `(abs(result)>0), 001`: the left part of the comma is discarded after evaluation and only the right part `001` is kept. – Christophe Oct 27 '18 at 09:20

0 Answers0