// Bisection Version 1 #include #include using namespace std; double f( double x ) { return( x * x - 2.0 ); } int main() { // User input ****************************** double x1 = 1.0; double x2 = 2.0; const double TOLERANCE = 1.0e-5; // ***************************************** double fx1 = f(x1), fx2 = f(x2), xp, xn, m, fm, error; if ( fx1 * fx2 >= 0.0 ) { cout << "STOP: Signs of f are not different at startup.\n\n"; system( "PAUSE" ); return( 0 ); } if ( fx1 > 0 ) xp = x1, xn = x2; else xp = x2, xn = x1; do { m = ( xn + xp ) / 2.0; fm = f(m); if ( fm == 0.0 ) { cout << "STOP: You have found the exact solution: x = " << m << "\n\n"; system( "PAUSE" ); return( 0 ); } else if ( fm > 0.0 ) xp = m; else xn = m; error = abs( xp - xn ); } while ( error > TOLERANCE ); cout << "The approximate solution is: x = " << ( xn + xp ) / 2.0; cout << "\n\n"; system( "PAUSE" ); return( 0 ); }