How do I avoid floating-point cancellation in C++?

Floating-point cancellation occurs when subtracting two nearly equal numbers, leading to significant loss of precision. In C++, you can minimize this issue by adopting various strategies such as scaling, using higher precision types, and reordering your arithmetic operations. Understanding these techniques is crucial for maintaining accuracy in numerical computations.

Example

// Example of avoiding floating-point cancellation double a = 1.0000001; double b = 1.0000002; // Direct subtraction may lead to cancellation double cancellation_result = a - b; // May lose precision // Better approach: Use a scaling factor double scale = 1e7; // Scaled to eliminate cancellation double better_result = (a * scale) - (b * scale); // Improved precision

Floating-point cancellation C++ numerical stability precision computation