// File: practice.cxx // Written by Michael and Allison // Demonstrates the bisection method to find a root to an equation. //---------------------------------------------------------------------------- #include #include #include using namespace std; //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // Prototypes: // This function finds a value that is within EPSILON for a root of F. // Preconditoin: F(low_x) <= 0 and F(high_x) >= 0. const double EPSILON = 1e-4; #define F(x) (3*x*x - 2*x - 9) double bisection(double low_x, double high_x); //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- int main() { cout << "One root of F is " << bisection(0.0, 1000.0) << endl; return EXIT_SUCCESS; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- double bisection(double low_x, double high_x) { double mid_x; assert(F(low_x) <= 0); assert(F(high_x) >= 0); while (abs(high_x - low_x) > EPSILON) { mid_x = (high_x + low_x)/2; if (F(mid_x) < 0) { low_x = mid_x; } else { high_x = mid_x; } } return (high_x + low_x)/2; } //----------------------------------------------------------------------------