// Chapter 4: three experiments with floating-point arithmetic. // Compile: g++ -std=c++11 ch04_roundoff.cpp -o ch04_roundoff // Run: ./ch04_roundoff // Use ordinary floating-point settings; do not enable fast-math. // The extra printed digits expose rounding; they do not add accuracy. #include #include #include #include int main() { // 1. Representation and precision. double a = 0.1, b = 0.2, c = 0.3; double s = a + b; float one_single = 1.0f, delta_single = 1.0e-8f; float single_sum = one_single + delta_single; double double_sum = 1.0 + 1.0e-8; std::cout << std::scientific << std::setprecision(16); std::cout << "1. Representation and precision\n"; std::cout << "0.1 + 0.2: " << std::setw(24) << s << '\n'; std::cout << "0.3: " << std::setw(24) << c << '\n'; std::cout << "Difference: " << std::setw(24) << s - c << '\n'; std::cout << "Gap above 1 (single): " << std::setw(24) << std::numeric_limits::epsilon() << '\n'; std::cout << "Gap above 1 (double): " << std::setw(24) << std::numeric_limits::epsilon() << '\n'; std::cout << "1 + 1e-8 (single): " << std::setw(24) << single_sum << '\n'; std::cout << "1 + 1e-8 (double): " << std::setw(24) << double_sum << '\n'; // 2. Cancellation. The stable expression is a reference, not exact arithmetic. std::cout << "\n2. Cancellation: sqrt(1+x) - 1\n"; std::cout << std::setw(12) << "x" << std::setw(24) << "Direct formula" << std::setw(24) << "Stable formula" << '\n'; for (int k = 2; k <= 18; k += 2) { double x = std::pow(10.0, -k); double direct = std::sqrt(1.0 + x) - 1.0; double stable = x / (std::sqrt(1.0 + x) + 1.0); std::cout << std::setprecision(2) << std::setw(12) << x << std::setprecision(16) << std::setw(24) << direct << std::setw(24) << stable << '\n'; } // 3. Order of summation. Store each intermediate result explicitly. a = 1.0e16; b = 1.0; c = -1.0e16; double temp = a + b; double first = temp + c; temp = a + c; double second = temp + b; std::cout << "\n3. Order of summation\n"; std::cout << "(a + b) + c: " << std::setw(24) << first << '\n'; std::cout << "(a + c) + b: " << std::setw(24) << second << '\n'; std::cout << "Exact sum: " << std::setw(24) << 1.0 << '\n'; return 0; }