// Bisection Version 2 #include #include using namespace std; double f( double x ) { return( x * x - 2.0 ); } int main() { // User input ****************************** double x1 = 1.0; double x2 = 3.0; const double TOLERANCE = 1.0e-9; const int MAX_ITERS = 150; // ***************************************** double fx1 = f(x1), fx2 = f(x2), xp, xn, m, fm, error; int count = 0; cout.precision( 8 ); if ( fx1 * fx2 < 0.0 ) { ( fx1 > 0 ) ? ( xp = x1, xn = x2 ) : ( xp = x2, xn = x1 ); do { m = ( xn + xp ) / 2.0; if ( ++count > MAX_ITERS ) { cout << "STOP: Maximum numbers of iterations exceeded.\n" << "Desired accuracy was probably not achieved.\n"; break; } if ( ( fm = f(m) ) == 0.0 ) { cout << "Congratulations! You have found the exact solution.\n"; xn = m, xp = m; break; } ( fm > 0.0 ) ? xp = m : xn = m; error = abs( xp - xn ); } while ( error > TOLERANCE ); cout << "Your solution is: x = " << ( xn + xp ) / 2.0; } else cout << "STOP: Signs of f are not different at startup.\n" << "Check your interval.\n"; cout << "\n\n"; system( "PAUSE" ); return( 0 ); }