// CS4414. Example 2. "Loss of significance" #include using namespace std; #include #include #define PRECISION float // Set precision level PRECISION f (PRECISION x ) { return (PRECISION) sqrt(x*x + 1.0) - 1.0; // function of interest } PRECISION better_form_of_f (PRECISION x ) { return x*x/( (PRECISION) sqrt(x*x + 1.0) + 1.0); // same thing. better form } main() { PRECISION x = 1.0; double Error = 100.0; // Output results: cout << endl; cout << endl; cout << "----Example ----Loss of significance in subtraction---------" << endl; cout << endl; cout << "x" << " " << "f(x) = sqrt(x^2 + 1) -1" << " " << "Same f(x) in different form" << endl; cout << endl; for (int i=0; i >= -20; i-- ) { x = pow(10.0, (PRECISION)(i) ); Error = 100.0*fabs( ( f(x) - better_form_of_f(x) )/ better_form_of_f(x) ); printf("%3.2e %s %10.8e %s %10.8e \n", x, " ", f(x), " ", better_form_of_f(x) ) ; } cout << endl; }